Debian Codegraph @

texk/texlive/linked_scripts/texdef/texdef.pl

raw
1 #!/usr/bin/env perl
2 ################################################################################
3 # texdef -- Show definitions of TeX commands
4 # Copyright (c) 2011-2025 Martin Scharrer <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19 ################################################################################
20 use strict;
21 use warnings;
22 use File::Temp qw/tempdir/;
23 use File::Basename;
24 use Cwd;
25
26 my ($scriptname) = fileparse($0, qw(\.pl \.perl));
27
28 my $TEX = 'pdflatex';
29 if ($scriptname =~ /^(.*)def$/) {
30 $TEX = $1;
31 }
32 my $TEXOPTIONS = " -interaction nonstopmode ";
33 my $USERTEXOPTIONS = "";
34
35 ## Variables for options and settings
36 my $CLASS = undef;
37 my $USERCLASS = 0;
38 my @PACKAGES = ();
39 my @OTHERDEFS = ();
40 my $INPREAMBLE = 0;
41 my $PRINTVERSION = 0;
42 my $TMPDIR = '';
43 my $SHOWVALUE = 0;
44 my $ISENVIRONMENT = 0;
45 my $PRINTORIGDEF = 0;
46 my $FINDDEF = 0;
47 my $LISTCMD = 0;
48 my $LISTCMDDEF = 0;
49 my $BEFORECLASS = 0;
50 my $PGFKEYS = 0;
51 my $PGFKEYSPLAIN = 0;
52 my $FAKECMD = "\0FAKECOMMAND\0";
53 my $EDIT = 0;
54 my $EDITOR;
55 my $EDITORCMDLN;
56 my @ENVCODE = ();
57 my %DEFS;
58 my $LISTSTR = '@TEXDEF@LISTDEFS@'; # used as a dummy command to list definitions
59 my @FILES; # List of files (sty, cls, ...)
60 my @FILEORDER; # Order of files
61 my %ALIAS; # list of aliases; required for registers
62 my $currfile = ''; # current file name
63 # Operating system:
64 my $OS = $^O;
65 my $WINDOWS = ($OS =~ /MSWin/);
66
67 my @IGNOREDEFREG = (# List of definitions to be ignored. Can be a regex or string
68 qr/^ver\@.*\.(?:sty|cls)$/,
69 qr/^opt\@.*\.(?:sty|cls)$/,
70 qr/^reserved\@[a-z]$/,
71 qr/-h\@\@k$/,
72 qr/^catcode\d+$/,
73 qr/^l\@ngrel\@x$/,
74 qr/^\@temp/,
75 qr/^KV\@/,
76 qr/^KVO\@/,
77 qr/^KVOdyn\@/,
78 qr/^KVS\@/,
79 qr/^currfile/,
80 qr/^filehook\@atbegin\@/,
81 qr/^filehook\@atend\@/,
82 qr/^count\d+$/,
83 qr/^pgfk@\//
84 );
85 my %IGNOREDEF = map { $_ => 1 } qw(
86 usepackage RequirePackage documentclass LoadClass @classoptionslist
87 CurrentOption tracingassigns in@@ escapechar
88 @unprocessedoptions @let@token @gtempa @filelist @filef@und
89 @declaredoptions @currnamestack @currname @currext
90 @ifdefinable default@ds ds@ @curroptions
91 filename@area filename@base filename@ext
92 );
93
94 ## Adds arguments to %IGNOREDEF
95 sub addignore {
96 my $opt = shift;
97 my $arg = shift;
98 my @args = split (/,/, $arg);
99 if ($opt eq 'ignore-cmds') {
100 @IGNOREDEF{@args} = (1) x scalar @args;
101 }
102 else {
103 push @IGNOREDEFREG, map { qr/$_/ } @args;
104 }
105 }
106
107 use Getopt::Long;
108 my $data = "file.dat";
109 my $length = 24;
110 my $verbose;
111
112 my $ISLATEX = 0;
113 my $ISTEX = 0;
114 my $ISCONTEXT = 0;
115
116 my $BEGINENVSTR = '%s';
117 my $ENDENVSTR = '%s';
118
119 my $VERSION = 'Version 1.10 -- 2025/02/17';
120 sub usage {
121 my $option = shift;
122 my $ret = ($option) ? 0 : 1;
123 print << 'EOT';
124 texdef -- Show definitions of TeX commands
125 Version 1.10 -- 2025/02/17
126 Copyright (c) 2011-2025 Martin Scharrer <[email protected]>
127 This program comes with ABSOLUTELY NO WARRANTY;
128 This is free software, and you are welcome to redistribute it under certain conditions;
129
130 Usage:
131 texdef [options] commandname [commandname ...]
132 latexdef [options] commandname [commandname ...]
133
134 Other program names are possible. See the 'tex' option. Command names do not need to start with `\`.
135
136 Options:
137 --tex <format>, -t <format> : Use given format of TeX: 'tex', 'latex', 'context'.
138 Variations of 'tex' and 'latex', like 'luatex', 'lualatex', 'xetex', 'xelatex' are supported.
139 The postfix '-dev' for develop versions of the format is also supported (e.g. 'latex-dev').
140 The default is given by the used program name: 'texdef' -> 'tex', 'latexdef' -> 'latex', etc.
141 --texoptions <options> : Call (La)TeX with the given options.
142 --source, -s : Try to show the original source code of the command definition (L).
143 --value, -v : Show value of command instead (i.e. \the\command).
144 --Environment, -E : Every command name is taken as an environment name. This will show the definition of
145 both \Macro\foo and \Macro\endfoo if \texttt{foo} is used as command name (L).
146 --preamble, -P : Show definition of the command inside the preamble.
147 --beforeclass, -B : Show definition of the command before \documentclass.
148 --package <pkg>, -p <pkg> : (M) Load given tex-file, package or module depending on whether '*tex', '*latex'
149 or 'context' is used. For LaTeX the <pkg> can start with `[<options>]` and end
150 with `<pkgname>` or `{<pkgname>}`.
151 --class <class>, -c <class> : (LaTeX only) Load given class instead of default ('article').
152 The <class> can start with `[<class options>]` and end
153 with `<classname>` or `{<classname>}`.
154 --environment <env>, -e <env> : (M) Show definition inside the given environment <env>.
155 --othercode <code>, -o <code> : (M) Add other code into the preamble before the definition is shown.
156 This can be used to e.g. load PGF/TikZ libraries.
157 --before <code>, -b <code> : (M) Place <code> before definition is shown.
158 The <code> can be arbitray TeX code and doesn't need be be balanced.
159 --after <code>, -a <code> : (M) Place <code> after definition is shown.
160 The <code> can be arbitray TeX code and doesn't need be be balanced.
161 --find, -f : Find file where the command sequence was defined (L).
162 --Find, -F : Show full filepath of the file where the command sequence was defined (L).
163 --list, -l : List user level command sequences of the given packages (L).
164 --list-defs, -L : List user level command sequences and their shorten definitions of the given packages (L).
165 --list-all, -ll : List all command sequences of the given packages (L).
166 --list-defs-all, -LL : List all command sequences and their shorten definitions of the given packages (L).
167 --ignore-cmds <cs,cs,..>, -i : Ignore the following command sequence(s) in the above lists. (M)
168 --ignore-regex <regex,..>, -I : Ignore all command sequences in the above lists which match the given Perl regular expression(s). (M)
169 --pgf-keys, -k : Takes commands as pgfkeys and displays their definitions. Keys must use the full path but the common '.\@cmd' prefix is applied.
170 --pgf-Keys, -K : Takes commands as pgfkeys and displays their definitions. Keys must use the full path.
171 --version, -V : If used alone prints version of this script.
172 (L) Together with -p or -c prints version of LaTeX package(s) or class, respectively.
173 --edit : Opens the file holding the macro definition. Uses --Find and --source. (L)
174 If the source definition can not be found the definition is printed as normal instead.
175 --editor <editor> : Can be used to set the used editor. If not used the environment variables TEXDEF_EDITOR, EDITOR and
176 SELECTED_EDITOR are read in this order. If none of these are set a list of default
177 editors are tried. The <editor> string can include '%f' for the filename, '%n' for
178 the line number and '%%' for a literal '%'. If no '%' is used '+%n %f' is added to
179 the given command.
180 --tempdir <directory> : Use given existing directory for temporary files.
181 --help, -h : Print this help and quit.
182
183 Long option can be shorten as long the are still unique. Short options can be combined.
184 If the option 'environment', 'before' and 'after' are used toegether the
185 produced code will be inserted in the given order (reversed order for 'after').
186 (M) = This option can be given multiple times.
187 (L) = LaTeX only. Requires the packages 'filehook' and 'currfile'.
188
189 Examples:
190 Show the definition of '\chapter' with different classes ('article' (default), 'book' and 'scrbook'):
191
192 latexdef chapter
193 latexdef -c book chapter
194 latexdef -c scrbook chapter
195
196 Show value of `\textwidth` with different class options:
197
198 latexdef -c [a4paper]{book} -v paperwidth
199 latexdef -c [letter]{book} -v paperwidth
200
201 Show definition of TikZ's '\draw' outside and inside a 'tikzpicture' environment:
202
203 latexdef -p tikz draw
204 latexdef -p tikz --env tikzpicture draw
205
206 Show definition of TikZ's '\draw' inside a node, inside a 'beamer' frame in 'handout' mode:
207
208 latexdef -c [handout]beamer -p tikz --env frame --env tikzpicture -b '\node {' -a '};' draw
209
210 List all user level command sequences (macros) defined by the 'xspace' LaTeX package:
211
212 latexdef -l -p xspace
213
214 EOT
215 exit ($ret);
216 }
217
218 sub envcode {
219 my $opt = shift;
220 my $arg = shift;
221 push @ENVCODE, [ $opt, $arg ];
222 }
223
224 ## Define and process options
225 Getopt::Long::Configure ("bundling","no_ignore_case");
226 GetOptions (
227 'value|v!' => \$SHOWVALUE,
228 'Environment|E!' => \$ISENVIRONMENT,
229 'version|V!' => \$PRINTVERSION,
230 'tempdir=s' => \$TMPDIR,
231 'find|f!' => sub { $FINDDEF = 1 },
232 'Find|F!' => sub { $FINDDEF = 2 },
233 'source|s!' => \$PRINTORIGDEF,
234 'list|l' => sub { $LISTCMD++ },
235 'list-def|L' => sub { $LISTCMDDEF++ },
236 'list-all' => sub { $LISTCMD=2 },
237 'list-def-all' => sub { $LISTCMDDEF=2 },
238 'ignore-cmds|i=s' => \&addignore,
239 'ignore-regex|I=s' => \&addignore,
240 'no-list|no-l' => sub { $LISTCMD=0; $LISTCMDDEF=0; },
241 'no-list-def|no-L' => sub { $LISTCMDDEF=0 },
242 'no-list-all|no-ll' => sub { $LISTCMD=0; $LISTCMDDEF=0; },
243 'no-list-def-all|no-LL' => sub { $LISTCMDDEF=0 },
244 'preamble|P!' => \$INPREAMBLE,
245 'beforeclass|B!' => \$BEFORECLASS,
246 'class|c=s' => \$CLASS,
247 'package|p=s' => \@PACKAGES,
248 'otherdefs|o=s' => \@OTHERDEFS,
249 'environment|e=s' => \&envcode,
250 'before|b=s' => \&envcode,
251 'after|a=s' => \&envcode,
252 'tex|t=s' => \$TEX,
253 'texoptions=s' => \$USERTEXOPTIONS,
254 'help|h' => \&usage,
255 'pgf-keys|k' => \$PGFKEYS,
256 'pgf-Keys|K' => \$PGFKEYSPLAIN,
257 'edit!' => sub { $EDIT=1; $FINDDEF = 2; $PRINTORIGDEF = 1; },
258 'editor=s' => \$EDITOR,
259 ) || usage();
260
261 # usage() unless @ARGV;
262
263 if ($EDIT && !$EDITOR) {
264 $EDITOR = $ENV{'TEXDEF_EDITOR'} || $ENV{'EDITOR'} || $ENV{'SELECTED_EDITOR'};
265 if (!$EDITOR) {
266 if (!$WINDOWS && exists $ENV{HOME}) {
267 # Check ~/.selected_editor file (Ubuntu)
268 my $fn = "$ENV{HOME}/.selected_editor";
269 if (-r $fn) {
270 open (my $fh, '<', $fn);
271 while (<$fh>) {
272 s/#.*//;
273 if (/^\s*SELECTED_EDITOR=(["']?)(.*)\1/) {
274 $EDITOR=$2;
275 }
276 }
277 close ($fh);
278 }
279 }
280 }
281 if (!$EDITOR) {
282 warn "No editor set. Using default!\n";
283 if ($WINDOWS) {
284 $EDITOR = 'texworks "%f"';
285 }
286 else {
287 for my $ed (qw(/usr/bin/vim /usr/bin/emacs /usr/bin/nano)) {
288 if (-x $ed) {
289 $EDITOR = $ed;
290 last;
291 }
292 }
293 if (!$EDITOR) {
294 for my $ed (qw(/usr/bin/editor /usr/bin/open /bin/open)) {
295 if (-x $ed) {
296 $EDITOR = "$ed \"%f\"";
297 last;
298 }
299 }
300 }
301 }
302 }
303 if (!$EDITOR) {
304 warn "No suitable editor found. Disable editing!\n";
305 $EDIT = 0;
306 }
307 }
308
309 ## Format specific settings
310 if ($TEX =~ /latex(?:-dev)?$/) {
311 $ISLATEX = 1;
312 $BEGINENVSTR = '\begin{%s}' . "\n";
313 $ENDENVSTR = '\end{%s}' . "\n";
314 }
315 elsif ($TEX =~ /tex(?:-dev)?$/) {
316 $ISTEX = 1;
317 $BEGINENVSTR = '\%s' . "\n";
318 $ENDENVSTR = '\end%s' . "\n";
319 }
320 elsif ($TEX =~ /context(?:-dev)?$/) {
321 $ISCONTEXT = 1;
322 $BEGINENVSTR = '\start%s' . "\n";
323 $ENDENVSTR = '\stop%s' . "\n";
324 }
325
326 if ($TEX =~ /^dvi((la)?tex)(?:-dev)?$/) {
327 $TEX = $1;
328 $TEXOPTIONS .= ' -output-format=dvi '
329 }
330
331 $USERCLASS = $CLASS;
332 $CLASS = 'article' if not $CLASS;
333 $CLASS =~ /^(?:\[(.*)\])?\{?(.*?)\}?$/;
334 $CLASS = $2;
335 my $CLASSOPTIONS = $1 || '';
336
337 if ($FINDDEF == 1 && !$ISLATEX) { die "Error: The --find / -f option is only implemented for LaTeX!\n"; }
338 if ($FINDDEF == 2 && !$ISLATEX) { die "Error: The --Find / -F option is only implemented for LaTeX!\n"; }
339
340 my @cmds = @ARGV;
341 $LISTCMD = $LISTCMDDEF if $LISTCMDDEF;
342 if ($LISTCMD && !$ISLATEX) { die "Error: Listing for commands is only implemented for LaTeX!\n"; }
343 if ($LISTCMD) {
344 @cmds = ($LISTSTR);
345 }
346
347 if ($PRINTVERSION) {
348 if (!@PACKAGES && !$USERCLASS) {
349 print STDERR "texdef: $VERSION\n";
350 exit (0) if not @cmds;
351 }
352 elsif (!@cmds) {
353 @cmds = ($FAKECMD);
354 }
355 }
356
357 sub print_versions {
358 my @files = map { $_.'.sty' } @PACKAGES;
359 unshift @files, "$USERCLASS.cls" if $USERCLASS;
360
361 foreach my $file (@files) {
362 print "\\message{^^J:TEXDEF: $file: \\csname ver\@$file\\endcsname^^J}%\n";
363 }
364 $PRINTVERSION = 0;# only print it once
365 }
366
367 usage() if not @cmds;
368
369 my $cwd = getcwd();
370 my $DIRSEP;
371 if ($WINDOWS) {
372 $DIRSEP = ';';
373 } else {
374 $DIRSEP = ':';
375 }
376 $ENV{TEXINPUTS} = '.' . $DIRSEP . $cwd . $DIRSEP . ($ENV{TEXINPUTS} || '');
377
378 if (!$TMPDIR) {
379 $TMPDIR = tempdir( 'texdef_XXXXXX', CLEANUP => 1, TMPDIR => 1 );
380 }
381 chdir $TMPDIR or die "Couldn't change into temporary directory '$TMPDIR'\n";
382 my $TMPFILE = 'texdeftmp.tex';
383
384 sub testdef {
385 my $cmd = shift;
386 my $def = shift;
387 if ($def eq 'macro:->\@latex@error {Can be used only in preamble}\@eha ' && $cmd ne '\@notprerr') {
388 unshift @cmds, '^' . $cmd;
389 }
390 elsif ($def =~ /^(?:\\[a-z]+ )?macro:.*?>(.*)/) {
391 my $macrodef = $1;
392 if ($macrodef =~ /^\\protect (.*?) ?$/) {
393 my $protectedmacro = $1;
394 unshift @cmds, $protectedmacro;
395 }
396 elsif ($macrodef =~ /^\\x\@protect (.*?) ?\\protect (.*?) ?$/) {
397 my $protectedmacro = $2;
398 unshift @cmds, $protectedmacro;
399 }
400 elsif ($macrodef =~ /^\\\@protected\@testopt \{?\\.*? \}? *(\\\\.*?) /) {
401 unshift @cmds, $1;
402 }
403 elsif ($macrodef =~ /^\\\@testopt \{?(\\.*?) \}?/) {
404 unshift @cmds, $1;
405 }
406 }
407 elsif ($def =~ /^\\(char|mathchar)|(dimen|skip|muskip|count)\d/) {
408 unshift @cmds, '#' . $cmd;
409 }
410 }
411
412 my $bschar = 0;
413 my $pcchar = 0;
414 my $lbchar = 0;
415 my $rbchar = 0;
416
417 sub special_chars {
418 return if (!$bschar && !$pcchar && !$lbchar && !$rbchar);
419 print '\begingroup'."\n";
420 if ($bschar) {
421 print '\lccode`.=92 \lowercase{\expandafter\gdef\csname @backslashchar\endcsname{.}}'."\n";
422 }
423 if ($pcchar) {
424 print '\lccode`.=37 \lowercase{\expandafter\gdef\csname @percentchar\endcsname{.}}'."\n";
425 }
426 if ($lbchar) {
427 print '\lccode`.=123 \lowercase{\expandafter\gdef\csname @charlb\endcsname{.}}'."\n";
428 }
429 if ($rbchar) {
430 print '\lccode`.=125 \lowercase{\expandafter\gdef\csname @charrb\endcsname{.}}'."\n";
431 }
432 print '\endgroup'."\n";
433 }
434
435 #######################################################################################################################
436 ## Loop around given commands ##
437 #######################################################################################################################
438 while (my $cmd = shift @cmds) {
439
440 next if $cmd eq '';
441 my $origcmd = $cmd;
442 my $showvalue;
443 my $inpreamble;
444 if ($cmd ne $FAKECMD) {
445 if ($PGFKEYS) {
446 $cmd = "pgfk\@$cmd/.\@cmd";
447 push @PACKAGES, "pgfkeys";
448 }
449 if ($PGFKEYSPLAIN) {
450 $cmd = "pgfk\@$cmd";
451 push @PACKAGES, "pgfkeys";
452 }
453 if (length ($cmd) > 1) {
454 $cmd =~ s/^([#^])?\\?//;
455 my $type = $1 || '';
456 $showvalue = $type eq '#';
457 $inpreamble = $type eq '^';
458 }
459 $bschar = $cmd =~ s/\\/\\csname\0\@backslashchar\\endcsname\0/g;
460 $pcchar = $cmd =~ s/\%/\\csname\0\@percentchar\\endcsname\0/g;
461 $lbchar = $cmd =~ s/\{/\\csname\0\@charlb\\endcsname\0/g;
462 $rbchar = $cmd =~ s/\}/\\csname\0\@charrb\\endcsname\0/g;
463 $cmd =~ s/\s/\\space /g;
464 $cmd =~ s/\0/ /g;
465 }
466
467 open (my $tmpfile, '>', $TMPFILE);
468 select $tmpfile;
469
470 print "\\nonstopmode\n";
471
472 if ($ISLATEX) {
473 #print "\\nofiles\n";
474 if ($FINDDEF || $LISTCMD || $PRINTORIGDEF) {
475 # Load the 'filehook' and 'currfile' packages without 'kvoptions' by providing dummy definitions for the 'currfile' options:
476 print '\makeatletter\expandafter\def\csname [email protected]\endcsname{0000/00/00}\let\SetupKeyvalOptions\@gobble';
477 print '\newcommand\DeclareStringOption[2][]{}';
478 print '\newcommand\DeclareBoolOption[2][false]{\expandafter\newif\csname ifcurrfile@#2\endcsname\csname currfile@#2#1\endcsname}';
479 print '\let\DeclareVoidOption\@gobbletwo\def\ProcessKeyvalOptions{\@ifstar{}{}}';
480 print '\def\currfile@mainext{tex}\def\currfile@maindir{\@currdir}\let\ifcurrfile@fink\iffalse\makeatother';
481 print "\\RequirePackage{filehook}\n";
482 print "\\RequirePackage{currfile}\n";
483 print '\makeatletter\expandafter\let\csname [email protected]\endcsname\relax\let\SetupKeyvalOptions\@undefined\let\DeclareBoolOption\@undefined\let\DeclareStringOption\@undefined';
484 print '\let\DeclareVoidOption\@undefined\let\ProcessKeyvalOptions\@undefined\makeatother';
485 }
486 if ($FINDDEF || $PRINTORIGDEF) {
487 print '{\expandafter}\expandafter\ifx\csname ' . $cmd . '\expandafter\endcsname\csname @undefined\endcsname' . "\n";
488 print '\AtBeginOfFiles{{{\expandafter}\expandafter\ifx\csname ' . $cmd . '\expandafter\endcsname\csname @undefined\endcsname\else' . "\n";
489 print ' \ClearHook\AtBeginOfFiles{}\relax';
490 print ' \ClearHook\AtEndOfFiles{}\relax';
491 # Get parent filename
492 print ' \csname currfile@pop\endcsname';
493 print ' {\message{^^J:: \expandafter\string\csname '.$cmd.'\endcsname\space first defined in "\currfilename".^^J}}\fi}}', "\n";
494 print ' \csname currfile@push\endcsname';
495 print '\AtEndOfFiles{{{\expandafter}\expandafter\ifx\csname ' . $cmd . '\expandafter\endcsname\csname @undefined\endcsname\else' . "\n";
496 print ' \ClearHook\AtBeginOfFiles{}\relax';
497 print ' \ClearHook\AtEndOfFiles{}\relax';
498 print ' {\message{^^J:: \expandafter\string\csname '.$cmd.'\endcsname\space first defined in "\currfilename".^^J}}\fi}}', "\n";
499 print '\else'. "\n";
500 print ' {\message{^^J:: \expandafter\string\csname '.$cmd.'\endcsname\space is defined by (La)TeX.^^J}}', "\n";
501 print '\fi'. "\n";
502 }
503 if ($LISTCMD) {
504 print '\AtBeginOfEveryFile{\message{^^J>> entering file "\currfilename"^^J}}'."\n";
505 print '\AtEndOfEveryFile{\message{^^J<< leaving file "\currfilename"^^J}}'."\n";
506 }
507 if (!$BEFORECLASS) {
508 print "\\documentclass[$CLASSOPTIONS]{$CLASS}\n";
509 if ($LISTCMD) {
510 print '\tracingonline=1\relax'. "\n";
511 print '\tracingassigns=1\relax'. "\n";
512 }
513
514 foreach my $pkg (@PACKAGES) {
515 $pkg =~ /^(?:\[(.*)\])?\{?(.*?)\}?$/;
516 my ($pkgname,$pkgoptions) = ($2, $1 || '');
517 print "\\usepackage[$pkgoptions]{$pkgname}\n";
518 }
519 {
520 local $, = "\n";
521 print @OTHERDEFS, '';
522 }
523 unless ($inpreamble || $INPREAMBLE) {
524 print_versions if $PRINTVERSION;
525 print '\tracingonline=0\relax'. "\n";
526 print '\tracingassigns=0\relax'. "\n";
527 print "\\begin{document}\n";
528 }
529 }
530 else {
531 if ($LISTCMD) {
532 print '\tracingonline=1\relax'. "\n";
533 print '\tracingassigns=1\relax'. "\n";
534 }
535 }
536 }
537 elsif ($ISCONTEXT) {
538 foreach my $pkgname (@PACKAGES) {
539 print "\\usemodule[$pkgname]\n";
540 }
541 {
542 local $, = "\n";
543 print @OTHERDEFS, '';
544 }
545 &special_chars();
546 print "\\starttext\n" unless $inpreamble || $INPREAMBLE;
547 }
548 elsif ($ISTEX) {
549 foreach my $pkgname (@PACKAGES) {
550 print "\\input $pkgname \n";
551 }
552 {
553 local $, = "\n";
554 print @OTHERDEFS, '';
555 }
556 &special_chars();
557 }
558
559 foreach my $envc (@ENVCODE) {
560 my ($envtype,$env) = @$envc;
561 if ($envtype eq 'environment') {
562 printf $BEGINENVSTR, $env;
563 }
564 elsif ($envtype eq 'before') {
565 print "$env\n";
566 }
567 }
568
569 if (!$LISTCMD && $cmd ne $FAKECMD) {
570
571 print '\immediate\write0{==============================================================================}%'."\n";
572 if (length ($cmd) > 1) {
573 if ($showvalue || $SHOWVALUE) {
574 print '\immediate\write0{\string\the\expandafter\string\csname ', $cmd, '\endcsname}%'."\n";
575 print '\immediate\write0{------------------------------------------------------------------------------}%'."\n";
576 print '\immediate\write0{\expandafter\the\csname ', $cmd, '\endcsname}%'."\n";
577 } else {
578 print '\begingroup';
579 print '\immediate\write0{\expandafter\string\csname ', $cmd, '\endcsname}%'."\n";
580 print '\immediate\write0{------------------------------------------------------------------------------}%'."\n";
581 print '\expandafter\endgroup\expandafter\immediate\expandafter\write\expandafter0\expandafter{\expandafter\meaning\csname ', $cmd, '\endcsname}%'."\n";
582 }
583 }
584 else {
585 if ($showvalue || $SHOWVALUE) {
586 print '\immediate\write0{\string\the\string\\', $cmd, '}%'."\n";
587 print '\immediate\write0{------------------------------------------------------------------------------}%'."\n";
588 print '\immediate\write0{\the\\', $cmd, '}%'."\n";
589 } else {
590 print '\immediate\write0{\string\\', $cmd, '}%'."\n";
591 print '\immediate\write0{------------------------------------------------------------------------------}%'."\n";
592 print '\immediate\write0{\meaning\\', $cmd, '}%'."\n";
593 }
594 }
595 print '\immediate\write0{==============================================================================}%'."\n";
596
597 }
598
599 foreach my $envc (reverse @ENVCODE) {
600 my ($envtype,$env) = @$envc;
601 if ($envtype eq 'environment') {
602 printf $ENDENVSTR, $env;
603 }
604 elsif ($envtype eq 'after') {
605 print "$env\n";
606 }
607 }
608
609 if ($ISLATEX) {
610 print "\\documentclass[$CLASSOPTIONS]{$CLASS}\n" if $BEFORECLASS;
611 if ($inpreamble || $INPREAMBLE || $BEFORECLASS) {
612 print_versions if $PRINTVERSION;
613 print '\tracingonline=0\relax'. "\n";
614 print '\tracingassigns=0\relax'. "\n";
615 print "\\begin{document}\n"
616 }
617 print "\\end{document}\n";
618 }
619 elsif ($ISCONTEXT) {
620 print "\\starttext\n" if $inpreamble || $INPREAMBLE;
621 print "\\stoptext\n";
622 }
623 elsif ($ISTEX) {
624 print "\\bye\n";
625 }
626
627 close ($tmpfile);
628
629 select STDOUT;
630
631 # Removes all '{' and '}' characters which no real braces.
632 sub remove_invalid_braces {
633 $_[0] =~ s/\\[\\%]//g; # remove \\ and \%
634 $_[0] =~ s/%.*$//; # remove line comments
635 $_[0] =~ s/\\[\{\}]//g; # remove \{ and \}
636 }
637
638 sub env_braces {
639 my $line = shift;
640 remove_invalid_braces $line;
641 my $level = shift || 0;
642 my $count = shift || 0;
643 for my $char (split //, $line) {
644 if ($char eq '{') {
645 $level++;
646 }
647 elsif ($char eq '}') {
648 $level--;
649 if ($level == 0) {
650 $count++;
651 }
652 }
653 }
654 return ($level, $count);
655 }
656
657 sub call_editor {
658 my $path = shift;
659 my $linenumber = shift;
660 print "Opening file '$path', line $linenumber.\n";
661 if ($EDITOR =~ /%/) {
662 $EDITOR =~ s/%%/\000/;
663 $EDITOR =~ s/%f/$path/;
664 $EDITOR =~ s/%n/$linenumber/;
665 $EDITOR =~ s/\000/%/;
666 system($EDITOR);
667 }
668 else {
669 system($EDITOR, "+$linenumber", $path);
670 }
671 }
672
673 sub print_orig_def {
674 my $rmacroname = shift;
675 my $file = shift;
676 my $path = shift;
677 my $linenumber;
678 my $found = 0;
679 open (my $fh, '<', $path) or return;
680 my $rmacrodef = qr/
681 ^ # Begin of line (no whitespaces!)
682 (
683 (?:(?:\\global|\\long|\\protected|\\outer)\s*)* # Prefixes (maybe with whitespace between them)
684 )
685 \\(
686 (?:[gex]?def) \s* \\ # TeX definitions
687 | (?:new|renew|provide)command\s* \*? \s* \{? \s* \\ # LaTeX definitions
688 | (?:new|renew|provide)robustcmd\s* \*? \s* \{? \s* \\ # etoolbox definitions
689 | (?:new(?:box|count|dimen|if|insert|read|skip|muskip|toks|write)) \s* \\ # TeX registers etc.
690 | (?:char|count|dimen|mathchar|skip|toks)def \s* \\ # TeX chardefs etc.
691 | \@namedef\{? # Definition by name only
692 | Declare[a-zA-z]+ \s* \*? \s* \{? \s* \\ # Declare... definitions
693 | declare[a-zA-z]+ \s* \*? \s* \{? \s* \\ # declare... definitions
694 )
695 $rmacroname # Macro name without backslash
696 [^a-zA-Z@]
697 /xms;
698 my $rmacrolet = qr/
699 ^ # Begin of line (no whitespaces!)
700 (?:global\s*)? # Prefixes (maybe with whitespace between them)
701 \\let \s* \\ # let
702 $rmacroname # Macro name without backslash
703 \s* =? # Optional '='
704 \s* \\ ([a-zA-Z@]+) # Second macro
705 /xms;
706 my $renvdef = qr/
707 ^ # Begin of line (no whitespaces!)
708 \\(
709 (?:new|renew|provide)environment\s* \{ \s* # LaTeX definitions
710 )
711 ($rmacroname) # Environment names follow same rules as macro names
712 \s* } # closing brace
713 (.*) # Rest of line
714 /xms;
715 while (my $line = <$fh>) {
716 if ($line =~ $rmacrodef) {
717 my $defcmd = $1;
718 $found = 1;
719 $linenumber = $.;
720 if ($EDIT) {
721 call_editor($path, $linenumber);
722 last;
723 }
724 print "% $file, line $linenumber:\n";
725 print $line;
726 last if $defcmd =~ /^(?:new(?:box|count|dimen|if|insert|read|skip|muskip|toks|write))/;
727 last if $defcmd =~ /^(?:char|count|dimen|mathchar|skip|toks)def/;
728 remove_invalid_braces $line;
729 my $obrace = $line =~ tr/{/{/;
730 my $cbrace = $line =~ tr/}/}/;
731 while ($obrace != $cbrace) {
732 my $line = <$fh>;
733 print $line;
734 remove_invalid_braces $line;
735 $obrace += $line =~ tr/{/{/;
736 $cbrace += $line =~ tr/}/}/;
737 }
738 print "\n";
739 last;
740 }
741 elsif ($line =~ $rmacrolet) {
742 my $letcmd = $1;
743 $found = 1;
744 $linenumber = $.;
745 if ($EDIT) {
746 call_editor($path, $linenumber);
747 last;
748 }
749 print "% $file, line $linenumber:\n";
750 print $line;
751 print "\n";
752 unshift @cmds, $letcmd;
753 last;
754 }
755 elsif ($line =~ $renvdef) {
756 $found = 2;
757 $linenumber = $.;
758 if ($EDIT) {
759 call_editor($path, $linenumber);
760 last;
761 }
762 print "% $file, line $linenumber:\n";
763 print $line;
764 my ($level, $count) = env_braces $line;
765 while ($count < 3) {
766 my $line = <$fh>;
767 print $line;
768 ($level, $count) = env_braces $line, $level, $count;
769 }
770 print "\n";
771 last;
772 }
773 }
774 close($fh);
775 return $found;
776 }
777
778 sub cleanpath {
779 my $path = shift;
780 chomp $path;
781 if ($path =~ /[a-z]:/i) {
782 $path =~ s/\//\\/g;
783 }
784 return $path;
785 }
786
787
788 open (my $texpipe, '-|', "$TEX $TEXOPTIONS $USERTEXOPTIONS \"$TMPFILE\" ");
789
790 my $name = '';
791 my $definition = '';
792 my $errormsg = '';
793 my $origdeffound = 0;
794
795 while (<$texpipe>) {
796 if (/^::\s*(.*)/) {
797 my $line = $1;
798 if ($FINDDEF == 2) {
799 if ($line =~ /first defined in "(.*)"/) {
800 my $path = cleanpath(`kpsewhich "$1"`);
801 $line =~ s/$1/$path/;
802 }
803 }
804 if ($PRINTORIGDEF) {
805 if ($line =~ /first defined in "(.*)"/) {
806 my $file = $1;
807 my $path = cleanpath(`kpsewhich "$file"`);
808 chomp $path;
809 $origdeffound = print_orig_def($cmd, $file, $path);
810 }
811 elsif ($line =~ /is defined by \(La\)TeX./) {
812 my $file = 'latex.ltx';
813 my $path = cleanpath(`kpsewhich "$file"`);
814 chomp $path;
815 $file = $path if $FINDDEF > 1;
816 $origdeffound = print_orig_def($cmd, $file, $path);
817 }
818 if (!$origdeffound) {
819 print "Source code definition of '$origcmd' could not be found.\n";
820 print "$line\n";
821 }
822 }
823 else {
824 print "$line\n";
825 }
826 next;
827 }
828 if (/^(:TEXDEF:\s*(.*))/) {
829 my $line = $1;
830 chomp ($line);
831 my $text = $2;
832 while (length $line >= 79) {
833 $line = <$texpipe>;
834 chomp ($line);
835 $text .= $line;
836 }
837 print "$text\n";
838 next;
839 }
840 if ($LISTCMD) {
841 if (/^>> entering file "(.*)"$/) {
842 push @FILES, $currfile;
843 $currfile = $1;
844 push @FILEORDER, $currfile if not exists $DEFS{$currfile};
845 }
846 elsif (/^<< leaving file "(.*)"$/) {
847 $currfile = pop @FILES;
848 }
849 elsif (/^{(?:into|reassigning) \s*(.*)}?$/) {
850 my ($cs, $def) = split (/=/, $1, 2);
851 $cs =~ s/^\\//;
852 $def =~ s/\}$//;
853 if ($LISTCMD > 1 || $cs !~ /[@ ]/) {
854 if ($def =~ /^\\((?:skip|count|toks|muskip|box|dimen)\d+)$/) {
855 $ALIAS{$1} = $cs;
856 }
857 elsif (exists $ALIAS{$cs}) {
858 $cs = $ALIAS{$cs}
859 }
860 $DEFS{$currfile}{$cs} = $def;
861 }
862 }
863 }
864 last if /^=+$/;
865 if ($_ =~ /^!\s*(.*)/ && !$errormsg) {
866 chomp;
867 my $line = $1;
868 $errormsg = $line;
869 while (length $line >= 79) {
870 $line = <$texpipe>;
871 chomp $line;
872 $errormsg .= $line;
873 }
874 }
875 }
876 while (<$texpipe>) {
877 last if /^-+$/;
878 next if /^$/;
879 chomp;
880 $name .= $_;
881 }
882 while (<$texpipe>) {
883 last if /^=+$/;
884 next if /^$/;
885 chomp;
886 $definition .= $_;
887 if ($_ =~ /^!\s*(.*)/ && !$errormsg) {
888 $errormsg = $1;
889 }
890 }
891 while (<$texpipe>) {
892 if ($_ =~ /^!\s*(.*)/ && !$errormsg) {
893 chomp;
894 my $line = $1;
895 $errormsg = $line;
896 while (length $line >= 79) {
897 $line = <$texpipe>;
898 chomp $line;
899 $errormsg .= $line;
900 }
901 }
902 }
903 close ($texpipe);
904
905 my $error = $? >> 8;
906
907 if ($error) {
908 if ( ($SHOWVALUE || $showvalue) && ($errormsg =~ /^You can't use `.*' after \\the\./) ) {
909 print STDERR "\n$name:\nError: Given command sequence does not contain a value.\n\n";
910 }
911 else {
912 print STDERR "\n$name:\nCompile error: $errormsg\n\n";
913 }
914 next;
915 }
916
917 #last if $PRINTORIGDEF && $origdeffound && $EDIT;
918
919 next if $cmd eq $FAKECMD;
920 if ($cmd eq $LISTSTR) {
921 foreach $currfile (@FILEORDER) {
922 next if not keys %{$DEFS{$currfile}};
923 print "\nDefined by file '$currfile':\n";
924 CMD:
925 foreach my $cmd (sort keys %{$DEFS{$currfile}}) {
926 next CMD if exists $IGNOREDEF{$cmd};
927 foreach my $pattern (@IGNOREDEFREG) {
928 next CMD if $cmd =~ $pattern;
929 }
930 print "\\$cmd";
931 print ": $DEFS{$currfile}{$cmd}" if ($LISTCMDDEF);
932 print "\n";
933 }
934 }
935 } elsif (!$PRINTORIGDEF || !$origdeffound) {
936 print "\n(in preamble)" if $inpreamble;
937 print "\n$name:\n$definition\n\n";
938 }
939
940 if (!($PRINTORIGDEF && $origdeffound)) {
941 testdef($origcmd,$definition);
942 }
943 if ($ISENVIRONMENT && $origdeffound < 2 && $cmd !~ /^end/) {
944 unshift @cmds, 'end' . $cmd;
945 }
946
947 }
948
949 chdir $cwd;
950 __END__