Debian Codegraph @

texk/texlive/linked_scripts/texcount/texcount.pl

raw
1 #! /usr/bin/env perl
2 use strict;
3 use warnings;
4 use utf8; # Because the script itself is UTF-8 encoded
5 use Encode;
6 use Text::Wrap;
7 use Term::ANSIColor;
8
9 # System variables
10 my $terminalwidth;
11
12 # Conditional package inclusion
13 if ($^O=~/^MSWin/) {
14 eval {
15 require Win32::Console::ANSI;
16 import Win32::Console::ANSI;
17 };
18 if ($@) {
19 option_ansi_colours(0);
20 print STDERR "NOTE: Package Win32::Console::ANSI required for colour coded output.\n";
21 }
22 }
23
24 # Terminal or not
25 if (-t STDOUT) { # If in terminal
26 eval {
27 require Term::ReadKey;
28 import Term::ReadKey;
29 ($terminalwidth)=GetTerminalSize();
30 };
31 } else {
32 option_ansi_colours(0);
33 }
34
35 if (!defined $terminalwidth) {$terminalwidth=76;}
36 elsif ($terminalwidth<60) {$terminalwidth=60;}
37 elsif ($terminalwidth>120) {$terminalwidth=120;}
38
39
40 ##### Version information
41
42 my $versionnumber="3.1.1";
43 my $versiondate="2018 Oct 28";
44
45 ###### Set global constants and names
46
47 ### Global data about TeXcount
48 my %GLOBALDATA=
49 ('versionnumber' => $versionnumber
50 ,'versiondate' => $versiondate
51 ,'maintainer' => 'Einar Andreas Rodland'
52 ,'copyrightyears' => '2008-2018'
53 ,'website' => 'http://app.uio.no/ifi/texcount/'
54 );
55
56 ### Named constants
57 my ($INCLUDE_NONE,$INCLUDE_AFTER,$INCLUDE_MERGE)=(0,1,2); # Value of $includeTeX
58 my ($HTML_NONE,$HTML_CORE,$HTML_FULL)=(0,1,2); # Value of $htmlstyle
59
60
61
62 ###### Set global settings and variables
63
64 ### Options and states
65
66 # Outer object (for error reports not added by a TeX object)
67 my $Main=getMain();
68
69 # Global options and settings
70 my $htmlstyle=$HTML_NONE; # Flag to print HTML
71 my $texcodeoutput=0; # Flag to convert output to valid TeX text
72 my $encoding=undef; # Selected input encoding (default will be guess)
73 my @encodingGuessOrder=qw/ascii utf8 latin1/; # Encoding guessing order
74 my $outputEncoding; # Encoding used for output
75 my @AlphabetScripts=qw/Digit Is_alphabetic/; # Letters minus logograms: defined later
76 my @LogogramScripts=qw/Ideographic Katakana Hiragana Thai Lao Hangul/; # Scripts counted as whole words
77
78 # Parsing rules options
79 my $includeTeX=$INCLUDE_NONE; # Flag to parse included files
80 my $includeBibliography=0; # Flag to include bibliography
81 my %substitutions; # Substitutions to make globally
82 my %IncludedPackages; # List of included packages
83
84 # Counting options
85 my @sumweights; # Set count weights for computing sum
86 my $optionWordFreq=0; # Count words of this frequency, or don't count if 0
87 my $optionWordClassFreq=0; # Count words per word class (language) if set
88 my $optionMacroStat=0; # Count macro, environment and package usage
89
90 # Parsing details options
91 my $strictness=0; # Flag to check for undefined environments
92 my $defaultVerbosity='0'; # Specification of default verbose output style
93 my $defaultprintlevel=0; # Flag indicating default level of verbose output
94 my $printlevel=undef; # Flag indicating level of verbose output
95 my $showstates=0; # Flag to show internal state in verbose log
96 my $showcodes=1; # Flag to show overview of colour codes (2=force)
97 my $showsubcounts=0; # Write subcounts if #>this, or not (if 0)
98 my $separatorstyleregex='^word'; # Styles (regex) after which separator should be added
99 my $separator=''; # Separator to add after words/tokens
100
101 # Final summary output options
102 my $showVersion=0; # Indicator that version info be included (1) or not (-1)
103 my $totalflag=0; # Flag to write only total summary
104 my $briefsum=0; # Flag to set brief summary
105 my $outputtemplate; # Output template
106 my $finalLineBreak=1; # Add line break at end
107
108 # Global settings
109 my $optionFast=1; # Flag inticating fast method
110
111 # Global variables and internal states (for internal use only)
112 my $blankline=0; # Number of blank lines printed
113 my $errorcount=0; # Number of errors in parsing
114 my %warnings=(); # Warnings
115 my %WordFreq; # Hash for counting words
116 my %MacroUsage; # Hash for counting macros, environments and packages
117
118 # External sources
119 my $HTMLfile; # HTML file to use as HTML output template
120 my $CSSfile; # CSS file to use with HTML output
121 my $CSShref; # CSS reference to use with HTML output
122 my @htmlhead; # Lines to add to the HTML header
123 my $htmlopen; # text used to open the HTML file
124 my $htmlclose; # text used to close the HTML file
125
126 # String data storage
127 my $STRINGDATA;
128
129 # Other constants
130 my $_PARAM_='<param>'; # to identify parameter to _parse_unit
131 my $STRING_PARAMETER='{_}'; # used to log macro parameters
132 my $STRING_OPTIONAL_PARAM='[_]'; # used to log optional parameter
133 my $STRING_GOBBLED_OPTION='[]'; # used to log gobbled macro option
134 my $STRING_ERROR='<error>'; # used to log errors causing parsing to stop
135 my $REGEX_NUMBER=qr/^\d+$/; # regex to recognize a number
136
137
138 ###### Set CMD specific settings and variables
139
140 ## Preset command line options
141 # List of options (stings) separated by comma,
142 # e.g. ('-inc','-v') to parse included files and
143 # give verbose output by default.
144 my @StartupOptions=();
145
146 # CMD specific global variables
147 my @filelist; # List of files to parse
148 my $globalworkdir='./'; # Overrules workdir (default=present root)
149 my $workdir; # Current directory (default=taken from filename)
150 my $auxdir; # Directory for auxilary files, e.g. bbl (default=$workdir)
151 my $fileFromSTDIN=0; # Flag to set input from STDIN
152 my $_STDIN_='<STDIN>'; # File name to represent STDIN (must be '<...>'!)
153
154 # CMD specific settings
155 $Text::Wrap::columns=$terminalwidth; # Page width for wrapped output
156
157
158 ###### Set state identifiers and methods
159
160
161 ### Counter indices from 0 to $SIZE_CNT-1
162 # 0: Number of files
163 # 1: Text words
164 # 2: Header words
165 # 3: Caption words
166 # 4: Number of headers
167 # 5: Number of floating environments
168 # 6: Number of inlined math
169 # 7: Number of displayed math
170 my $SIZE_CNT=8;
171 my $SIZE_CNT_DEFAULT=8;
172 my $CNT_FILE=0;
173 my $CNT_WORDS_TEXT=1;
174 my $CNT_WORDS_HEADER=2;
175 my $CNT_WORDS_OTHER=3;
176 my $CNT_COUNT_HEADER=4;
177 my $CNT_COUNT_FLOAT=5;
178 my $CNT_COUNT_INLINEMATH=6;
179 my $CNT_COUNT_DISPLAYMATH=7;
180
181 # Labels used to describe the counts
182 my @countkey=('file','word','hword','oword','header','float','inmath','dsmath');
183 my @countdesc=('Files','Words in text','Words in headers',
184 'Words outside text (captions, etc.)','Number of headers','Number of floats/tables/figures',
185 'Number of math inlines','Number of math displayed');
186
187 # Map keywords to counters
188 my %key2cnt;
189 add_keys_to_hash(\%key2cnt,$CNT_FILE,0,'file');
190 add_keys_to_hash(\%key2cnt,$CNT_WORDS_TEXT,1,'text','word','w','wd');
191 add_keys_to_hash(\%key2cnt,$CNT_WORDS_HEADER,2,'headerword','hword','hw','hwd');
192 add_keys_to_hash(\%key2cnt,$CNT_WORDS_OTHER,3,'otherword','other','oword','ow','owd');
193 add_keys_to_hash(\%key2cnt,$CNT_COUNT_HEADER,4,'header','heading','head');
194 add_keys_to_hash(\%key2cnt,$CNT_COUNT_FLOAT,5,'float','table','figure');
195 add_keys_to_hash(\%key2cnt,$CNT_COUNT_INLINEMATH,6,'inline','inlinemath','imath','eq');
196 add_keys_to_hash(\%key2cnt,$CNT_COUNT_DISPLAYMATH,7,'displaymath','dsmath','dmath','ds');
197
198
199 ### Token types
200 # Set in $tex->{'type'} by call to _next_token
201 my $TOKEN_SPACE=-1;
202 my $TOKEN_COMMENT=0;
203 my $TOKEN_WORD=1; # word (or other form of text or text component)
204 my $TOKEN_SYMBOL=2; # symbol (not word, e.g. punctuation)
205 my $TOKEN_MACRO=3; # macro (\name)
206 my $TOKEN_BRACE=4; # curly braces: { }
207 my $TOKEN_BRACKET=5; # brackets: [ ]
208 my $TOKEN_MATH=6;
209 my $TOKEN_LINEBREAK=9; # line break in file
210 my $TOKEN_TC=666; # TeXcount instructions (%TC:instr)
211 my $TOKEN_END=999; # end of line or blank line
212
213
214 ### Parsing states
215 #
216 ## States for regions that should not be counted
217 # IGNORE = exclude from count
218 # FLOAT = float (exclude, but include captions)
219 # EXCLUDE_STRONG = strong exclude, ignore environments
220 # EXCLUDE_STRONGER = stronger exclude, do not parse macro parameters
221 # EXCLUDE_ALL = ignore everything except end marker: even {
222 # PREAMBLE = preamble (between \documentclass and \begin{document})
223 ## States for regions in which words should be counted
224 # TEXT = text
225 # TEXT_HEADER = header text
226 # TEXT_FLOAT = float text
227 ## State change: not used in parsing, but to switch state then ignore contents
228 # TO_INLINEMATH = switch to inlined math
229 # TO_DISPLAYMATH = switch to displayed math
230 ## Other states
231 # _NULL = default state to use if none other is defined
232 # _OPTION = state used to indicate that the next parameter is an option
233 # _EXCLUDE_ = cutoff, state <= this represents excluded text
234 ## NB: Presently, it is assumed that additional states is added as 8,9,...,
235 ## e.g. that states added through TC:newcounter correspond to the added counters.
236 #
237 my $STATE_IGNORE=-1;
238 my $STATE_MATH=-2;
239 my $STATE_FLOAT=-10;
240 my $STATE_EXCLUDE_STRONG=-20;
241 my $STATE_EXCLUDE_STRONGER=-30;
242 my $STATE_EXCLUDE_ALL=-40;
243 my $STATE_SPECIAL_ARGUMENT=-90;
244 my $STATE_PREAMBLE=-99;
245 my $STATE_TEXT=1;
246 my $STATE_TEXT_HEADER=2;
247 my $STATE_TEXT_FLOAT=3;
248 my $STATE_TO_HEADER=4;
249 my $STATE_TO_FLOAT=5;
250 my $STATE_TO_INLINEMATH=6;
251 my $STATE_TO_DISPLAYMATH=7;
252 my $__STATE_EXCLUDE_=-10;
253 my $__STATE_NULL=1;
254 my $_STATE_OPTION=-1000;
255 my $_STATE_NOOPTION=-1001;
256 my $_STATE_AUTOOPTION=-1002;
257
258 # Counter key mapped to STATE
259 my $PREFIX_PARAM_OPTION=' '; # Prefix for parameter options/modifiers
260 my %key2state;
261 add_keys_to_hash(\%key2state,$STATE_TEXT,1,'text','word','w','wd');
262 add_keys_to_hash(\%key2state,$STATE_TEXT_HEADER,2,'headertext','headerword','hword','hw','hwd');
263 add_keys_to_hash(\%key2state,$STATE_TEXT_FLOAT,3,'otherword','other','oword','ow','owd');
264 add_keys_to_hash(\%key2state,$STATE_TO_HEADER,4,'header','heading','head');
265 add_keys_to_hash(\%key2state,$STATE_TO_FLOAT,5,'float','table','figure');
266 add_keys_to_hash(\%key2state,$STATE_TO_INLINEMATH,6,'inline','inlinemath','imath','eq');
267 add_keys_to_hash(\%key2state,$STATE_TO_DISPLAYMATH,7,'displaymath','dsmath','dmath','ds');
268 add_keys_to_hash(\%key2state,$STATE_IGNORE,0,'ignore','x');
269 add_keys_to_hash(\%key2state,$STATE_MATH,'ismath');
270 add_keys_to_hash(\%key2state,$STATE_FLOAT,-1,'isfloat');
271 add_keys_to_hash(\%key2state,$STATE_EXCLUDE_STRONG,-2,'xx');
272 add_keys_to_hash(\%key2state,$STATE_EXCLUDE_STRONGER,-3,'xxx');
273 add_keys_to_hash(\%key2state,$STATE_EXCLUDE_ALL,-4,'xall');
274 add_keys_to_hash(\%key2state,$STATE_SPECIAL_ARGUMENT,'specarg','spescialarg','specialargument');
275 add_keys_to_hash(\%key2state,$_STATE_OPTION,'[',' option',' opt',' optional');
276 add_keys_to_hash(\%key2state,$_STATE_NOOPTION,'nooption','nooptions','noopt','noopts');
277 add_keys_to_hash(\%key2state,$_STATE_AUTOOPTION,'autooption','autooptions','autoopt','autoopts');
278
279 # When combining two states, use the first one; list must be complete!
280 my @STATE_FIRST_PRIORITY=(
281 $STATE_EXCLUDE_ALL,
282 $STATE_EXCLUDE_STRONGER,
283 $STATE_EXCLUDE_STRONG,
284 $STATE_SPECIAL_ARGUMENT,
285 $STATE_FLOAT,
286 $STATE_MATH,
287 $STATE_IGNORE,
288 $STATE_PREAMBLE,
289 $STATE_TO_FLOAT,
290 $STATE_TO_HEADER,
291 $STATE_TO_INLINEMATH,
292 $STATE_TO_DISPLAYMATH);
293 my @STATE_MID_PRIORITY=();
294 my @STATE_LAST_PRIORITY=(
295 $STATE_TEXT_FLOAT,
296 $STATE_TEXT_HEADER,
297 $STATE_TEXT);
298
299 # Map state to corresponding word counter
300 my %state2cnt=(
301 $STATE_TEXT => $CNT_WORDS_TEXT,
302 $STATE_TEXT_HEADER => $CNT_WORDS_HEADER,
303 $STATE_TEXT_FLOAT => $CNT_WORDS_OTHER);
304
305 # Transition state mapped to content state and counter
306 my %transition2state=(
307 $STATE_TO_HEADER => [$STATE_TEXT_HEADER,$CNT_COUNT_HEADER],
308 $STATE_TO_INLINEMATH => [$STATE_MATH ,$CNT_COUNT_INLINEMATH],
309 $STATE_TO_DISPLAYMATH => [$STATE_MATH ,$CNT_COUNT_DISPLAYMATH],
310 $STATE_TO_FLOAT => [$STATE_FLOAT ,$CNT_COUNT_FLOAT]);
311
312 # Parsing state descriptions (used for macro rule help)
313 my %state2desc=(
314 $STATE_IGNORE => 'ignore: do not count',
315 $STATE_MATH => 'math/equation contents',
316 $STATE_FLOAT => 'float (figure, etc.): ignore all but special macros',
317 $STATE_EXCLUDE_STRONG => 'strong exclude: ignore environments',
318 $STATE_EXCLUDE_STRONGER => 'stronger exclude: ignore environments and macro paramters',
319 $STATE_EXCLUDE_ALL => 'exlude all: even {, only scan for end marker',
320 $STATE_PREAMBLE => 'preamble: from \documentclass to \begin{document}',
321 $STATE_SPECIAL_ARGUMENT => 'special macro argument that TeXcount may process further',
322 $STATE_TEXT => 'text: count words',
323 $STATE_TEXT_HEADER => 'header text: count words as header words',
324 $STATE_TEXT_FLOAT => 'float text: count words as float words (e.g. captions)',
325 $STATE_TO_HEADER => 'header: count header, then count words as header words',
326 $STATE_TO_FLOAT => 'float: count float, then count words as float/other words',
327 $STATE_TO_INLINEMATH => 'inline math: count as inline math/equation',
328 $STATE_TO_DISPLAYMATH => 'displayed math: count as displayed math/equation',
329 $_STATE_OPTION => 'rule for [] option follows',
330 $_STATE_NOOPTION => 'no [] options allowed here',
331 $_STATE_AUTOOPTION => 'automatic [] option gobbling');
332
333 # Short state name for each state for use with -showstates
334 my %state2key = ($STATE_PREAMBLE=>'pre');
335 for my $key ('x','xx','xxx','xall','w','hw','ow','eq','ds',
336 'head','float','isfloat','ismath','specarg') {
337 $state2key{$key2state{$key}}=$key;
338 }
339
340 # Parsing state presentation style
341 my %state2style=(
342 $STATE_TEXT => 'word',
343 $STATE_TEXT_HEADER => 'hword',
344 $STATE_TEXT_FLOAT => 'oword',
345 );
346
347 # State: is a text state..."include state" is more correct
348 sub state_is_text {
349 my $st=shift @_;
350 return ($st>=$STATE_TEXT);
351 }
352
353 # State: is a parsed/included region, text or preamble
354 sub state_is_parsed {
355 my $st=shift @_;
356 return ($st>=$STATE_TEXT || $st==$STATE_PREAMBLE);
357 }
358
359 # State: get CNT corresponding to text state (or undef)
360 sub state_text_cnt {
361 my $st=shift @_;
362 return $state2cnt{$st};
363 }
364
365 # State: is an exclude state
366 sub state_is_exclude {
367 my $st=shift @_;
368 return ($st<=$__STATE_EXCLUDE_);
369 }
370
371 # State: \begin and \end should be processed
372 sub state_inc_envir {
373 my $st=shift @_;
374 return ($st>$STATE_EXCLUDE_STRONG);
375 }
376
377 # State as text (used with printstate)
378 # TODO: Should do a conversion based on STATE values.
379 sub state_to_text {
380 my $st=shift @_;
381 my $statename = $state2key{$st};
382 if (defined $statename) {$st=$statename;}
383 return $st;
384 }
385
386 # Style to use with text state
387 sub state_to_style {
388 return $state2style{shift @_};
389 }
390
391 # Add new counter with the given key and description
392 sub add_new_counter {
393 my ($key,$desc,$like)=@_;
394 my $state=$SIZE_CNT;
395 my $cnt=$SIZE_CNT;
396 $key=lc($key);
397 if (!defined $like){$like=$CNT_WORDS_OTHER;}
398 $key2cnt{$key}=$cnt;
399 push @countkey,$key;
400 push @countdesc,$desc;
401 if (defined $sumweights[$like]) {$sumweights[$cnt]=$sumweights[$like];}
402 $key2state{$key}=$state;
403 $state2key{$state}=$key;
404 $state2cnt{$state}=$cnt;
405 $state2style{$state}='altwd';
406 push @STATE_MID_PRIORITY,$state;
407 $SIZE_CNT++;
408 }
409
410
411 ###### Set global definitions
412
413
414 ### Break points
415 # Definition of macros that define break points that start a new subcount.
416 # The values given are used as labels.
417 my %BreakPointsOptions;
418 $BreakPointsOptions{'none'}={};
419 $BreakPointsOptions{'part'}={%{$BreakPointsOptions{'none'}},'\part'=>'Part'};
420 $BreakPointsOptions{'chapter'}={%{$BreakPointsOptions{'part'}},'\chapter'=>'Chapter'};
421 $BreakPointsOptions{'section'}={%{$BreakPointsOptions{'chapter'}},'\section'=>'Section'};
422 $BreakPointsOptions{'subsection'}={%{$BreakPointsOptions{'section'}},'\subsection'=>'Subsection'};
423 $BreakPointsOptions{'default'}=$BreakPointsOptions{'subsection'};
424 my %BreakPoints=%{$BreakPointsOptions{'none'}};
425
426 ### Print styles
427 # Definition of different print styles: maps of class labels
428 # to ANSI codes. Class labels are as used by HTML styles.
429 my %STYLES;
430 my $STYLE_EMPTY=' ';
431 my $STYLE_BLOCK='-';
432 my $NOSTYLE=' ';
433 $STYLES{'Errors'}={'error'=>'bold red','note'=>'bold white'};
434 $STYLES{'Words'}={'word'=>'blue','hword'=>'bold blue','oword'=>'blue','altwd'=>'blue'};
435 $STYLES{'Macros'}={'cmd'=>'green','fileinc'=>'bold green','special'=>'bold red','specarg'=>'red'};
436 $STYLES{'Options'}={'option'=>'yellow','optparm'=>'green'};
437 $STYLES{'Ignored'}={'ignore'=>'cyan','math'=>'magenta'};
438 $STYLES{'Excluded'}={'exclcmd'=>'yellow','exclenv'=>'yellow','exclmath'=>'yellow','mathcmd'=>'yellow'};
439 $STYLES{'Groups'}={'document'=>'bold red','envir'=>'red','mathgroup'=>'magenta'};
440 $STYLES{'Comments'}={'tc'=>'bold yellow','comment'=>'yellow'};
441 $STYLES{'Sums'}={'cumsum'=>'yellow'};
442 $STYLES{'States'}={'state'=>'cyan underline'};
443 $STYLES{'<core>'}={%{$STYLES{'Errors'}},$STYLE_EMPTY=>$NOSTYLE,'<printlevel>'=>1,'note'=>'bold white'};
444 $STYLES{0}={%{$STYLES{'Errors'}},'<printlevel>'=>0,'note'=>'bold white'};
445 $STYLES{1}={%{$STYLES{'<core>'}},%{$STYLES{'Words'}},%{$STYLES{'Groups'}},%{$STYLES{'Sums'}}};
446 $STYLES{2}={%{$STYLES{1}},%{$STYLES{'Macros'}},%{$STYLES{'Ignored'}},%{$STYLES{'Excluded'}}};
447 $STYLES{3}={%{$STYLES{2}},%{$STYLES{'Options'}},%{$STYLES{'Comments'}},'<printlevel>'=>2};
448 $STYLES{4}={%{$STYLES{3}},%{$STYLES{'States'}}};
449 $STYLES{'All'}=$STYLES{4};
450 my %STYLE=%{$STYLES{$defaultVerbosity}};
451
452 my @STYLE_LIST=('error','word','hword','oword','altwd',
453 'ignore','document','special','cmd','exclcmd',
454 'option','optparm','envir','exclenv','specarg',
455 'mathgroup','exclmath','math','mathcmd','comment','tc','fileinc','state','cumsum');
456 my %STYLE_DESC=(
457 'error' => 'ERROR: TeXcount error message',
458 'word' => 'Text which is counted: counted as text words',
459 'hword' => 'Header and title text: counted as header words',
460 'oword' => 'Caption text and footnotes: counted as caption words',
461 'altwd' => 'Words in user specified counters: counted in separate counters',
462 'ignore' => 'Ignored text or code: excluded or ignored',
463 'document' => '\documentclass: document start, beginning of preamble',
464 'special' => 'Special macros, eg require special handling or have side-effects',
465 'cmd' => '\macro: macro not counted, but parameters may be',
466 'exclcmd' => '\macro: macro in excluded region',
467 'option' => '[Macro options]: not counted',
468 'optparm' => '[Optional parameter]: content parsed and styled as counted',
469 'specarg' => 'Special argument, eg with side-effects',
470 'envir' => '\begin{name} \end{name}: environment',
471 'exclenv' => '\begin{name} \end{name}: environment in excluded region',
472 'mathgroup' => '$ $: counted as one equation',
473 'exclmath' => '$ $: equation in excluded region',
474 'math' => '2+2=4: maths (inside $...$ etc.)',
475 'mathcmd' => '$\macro$: macros inside maths',
476 'comment' => '% Comments: not counted',
477 'tc' => '%TC:TeXcount instructions: not counted',
478 'fileinc' => 'File to include: not counted but file may be counted later',
479 'state' => '[state]: internal TeXcount state',
480 'cumsum' => '[cumsum]: cumulative sum count');
481
482
483 ###### Define what a word is and language options
484
485
486 # Patters matching a letter. Should be a single character or
487 # ()-enclosed regex for substitution into word pattern regex.
488 my @LetterMacros=qw/ae AE o O aa AA oe OE ss
489 alpha beta gamma delta epsilon zeta eta theta iota kappa lamda
490 mu nu xi pi rho sigma tau upsilon phi chi psi omega
491 Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega
492 /;
493 my $specialchars='\\\\('.join('|',@LetterMacros).')(\{\}|\s+|\b)';
494 my $modifiedchars='\\\\[\'\"\`\~\^\=](@|\{@\})';
495 my %NamedLetterPattern;
496 $NamedLetterPattern{'restricted'}='@';
497 $NamedLetterPattern{'default'}='('.join('|','@',$modifiedchars,$specialchars).')';
498 $NamedLetterPattern{'relaxed'}=$NamedLetterPattern{'default'};
499 my $LetterPattern=$NamedLetterPattern{'default'};
500
501 # List of regexp patterns that should be analysed as words.
502 # Use @ to represent a letter, will be substituted with $LetterPattern.
503 # Named patterns may replace or be appended to the original patterns.
504 # Apply_Options() results in a call to apply_language_options() which
505 # constructs $WordPattern based on $LetterPattern, @WordPatterns and
506 # alphabet/logogram settings.
507 my %NamedWordPattern;
508 $NamedWordPattern{'letters'}='@';
509 $NamedWordPattern{'words'}='(@+|@+\{@+\}|\{@+\}@+)([\-\'\.]?(@+|\{@+\}))*';
510 my @WordPatterns=($NamedWordPattern{'words'});
511 my $WordPattern; # Regex matching a word (defined in apply_language_options())
512
513 ### Macro option regexp list
514 # List of regexp patterns to be gobbled as macro option in and after
515 # a macro.
516 my %NamedMacroOptionPattern;
517 $NamedMacroOptionPattern{'default'}='\[[^\[\]\n]*\]';
518 $NamedMacroOptionPattern{'relaxed'}='\[\n?([^\[\]\n]\n?)*\]';
519 $NamedMacroOptionPattern{'restricted'}='\[(\w|[,\-\s\~\.\:\;\+\?\*\_\=])*\]';
520 my $MacroOptionPattern=$NamedMacroOptionPattern{'default'};
521
522 ### Alternative language encodings
523 my %NamedEncodingGuessOrder;
524 $NamedEncodingGuessOrder{'chinese'}=[qw/utf8 gb2312 big5/];
525 $NamedEncodingGuessOrder{'japanese'}=[qw/utf8 euc-jp iso-2022-jp jis shiftjis/];
526 $NamedEncodingGuessOrder{'korean'}=[qw/utf8 euc-kr iso-2022-kr/];
527
528
529
530 ###### Define character classes (alphabets)
531
532
533 ### Character classes to use as Unicode properties
534
535 # Character group representing digits 0-9 (more restrictive than Digits)
536 sub Is_digit { return <<END;
537 0030\t0039
538 END
539 }
540
541 # Character group representing letters (excluding logograms)
542 sub Is_alphabetic { return <<END;
543 +utf8::Alphabetic
544 -utf8::Ideographic
545 -utf8::Katakana
546 -utf8::Hiragana
547 -utf8::Thai
548 -utf8::Lao
549 -utf8::Hangul
550 END
551 }
552
553 # Character group representing letters (excluding logograms)
554 sub Is_alphanumeric { return <<END;
555 +utf8::Alphabetic
556 +utf8::Digit
557 -utf8::Ideographic
558 -utf8::Katakana
559 -utf8::Hiragana
560 -utf8::Thai
561 -utf8::Lao
562 -utf8::Hangul
563 END
564 }
565
566 # Character class for punctuation excluding special characters
567 sub Is_punctuation { return <<END;
568 +utf8::Punctuation
569 -0024\t0025
570 -005c
571 -007b\007e
572 END
573 }
574
575 # Character group representing CJK characters
576 sub Is_cjk { return <<END;
577 +utf8::Han
578 +utf8::Katakana
579 +utf8::Hiragana
580 +utf8::Hangul
581 END
582 }
583
584 # Character group for CJK punctuation characters
585 sub Is_cjkpunctuation { return <<END;
586 3000\t303f
587 2018\t201f
588 ff01\tff0f
589 ff1a\tff1f
590 ff3b\tff3f
591 ff5b\tff65
592 END
593 }
594
595
596 ###### Define core rules
597
598 ### Macros indicating package inclusion
599 # Will always be assumed to take one extra parameter which is the list of
600 # packages. Macro handling rule indicates parameters ignored prior to that.
601 # Gets added to TeXmacro. After that, values are not used, only membership.
602 # Handling is otherwise hard-coded rather than rule based.
603 my %TeXpackageinc;
604 add_keys_to_hash(\%TeXpackageinc,['[','ignore','specialargument'],'\usepackage','\RequirePackage');
605
606 ### Macros that are counted within the preamble
607 # The preamble is the text between \documentclass and \begin{document}.
608 # Text and macros in the preamble is ignored unless specified here. The
609 # value is the states (1=text, 2=header, etc.) they should be interpreted as.
610 # Note that only the first unit (token or {...} block) is counted.
611 # Gets added to TeXmacro. Is used within preambles only.
612 my %TeXpreamble;
613 add_keys_to_hash(\%TeXpreamble,['header'],'\title');
614 add_keys_to_hash(\%TeXpreamble,['other'],'\thanks');
615 add_keys_to_hash(\%TeXpreamble,['xxx','xxx'],'\newcommand','\renewcommand');
616 add_keys_to_hash(\%TeXpreamble,['xxx','xxx','xxx'],'\newenvironment','\renewenvironment');
617
618 ### In floats: include only specific macros
619 # Macros used to identify caption text within floats.
620 # Gets added to TeXmacro. Is used within floats only.
621 my %TeXfloatinc=('\caption'=>['otherword']);
622
623 ### How many tokens to gobble after macro
624 # Each macro is assumed to gobble up a given number of
625 # tokens (or {...} groups), as well as options [...] before, within
626 # and after. The %TeXmacro hash gives a link from a macro
627 # (or beginNAME for environment with no the backslash)
628 # to either an integer giving the number of tokens to ignore
629 # or to an array (specified as [rule,rule,...]) of length N where
630 # N is the number of parameters to be read with the macro. The
631 # array values tell how each is to be interpreted (see the parser state
632 # keywords for valid values). Thus specifying a number N is
633 # equivalent to specifying an array of N 'ignore' rules.
634 #
635 # For macros not specified here, the default value is 0: i.e.
636 # no tokens are excluded, but [...] options are.
637 my %TeXmacro=(%TeXpreamble,%TeXfloatinc,%TeXpackageinc);
638 add_keys_to_hash(\%TeXmacro,['text'],
639 '\textnormal','\textrm','\textit','\textbf','\textsf','\texttt','\textsc','\textsl','\textup','\textmd',
640 '\makebox','\mbox','\framebox','\fbox','\uppercase','\lowercase','\textsuperscript','\textsubscript',
641 '\citetext');
642 add_keys_to_hash(\%TeXmacro,['[','text'],
643 '\item');
644 add_keys_to_hash(\%TeXmacro,['[','ignore'],
645 '\linebreak','\nolinebreak','\pagebreak','\nopagebreak');
646 add_keys_to_hash(\%TeXmacro,0,
647 '\maketitle','\indent','\noindent',
648 '\centering','\raggedright','\raggedleft','\clearpage','\cleardoublepage','\newline','\newpage',
649 '\smallskip','\medskip','\bigskip','\vfill','\hfill','\hrulefill','\dotfill',
650 '\normalsize','\small','\footnotesize','\scriptsize','\tiny','\large','\Large','\LARGE','\huge','\Huge',
651 '\normalfont','\em','\rm','\it','\bf','\sf','\tt','\sc','\sl',
652 '\rmfamily','\sffamily','\ttfamily','\upshape','\itshape','\slshape','\scshape','\mdseries','\bfseries',
653 '\selectfont',
654 '\tableofcontents','\listoftables','\listoffigures');
655 add_keys_to_hash(\%TeXmacro,1,
656 '\begin','\end',
657 '\documentclass','\documentstyle','\hyphenation','\pagestyle','\thispagestyle',
658 '\author','\date',
659 '\bibliographystyle','\bibliography','\pagenumbering','\markright',
660 '\includeonly','\includegraphics','\special',
661 '\label','\ref','\pageref','\bibitem',
662 '\eqlabel','\eqref','\hspace','\vspace','\addvspace',
663 '\newsavebox','\usebox',
664 '\newlength','\newcounter','\stepcounter','\refstepcounter','\usecounter',
665 '\fontfamily','\fontseries',
666 '\alph','\arabic','\fnsymbol','\roman','\value',
667 '\typeout', '\typein','\cline');
668 add_keys_to_hash(\%TeXmacro,2,
669 '\newfont','\newtheorem','\sbox','\savebox','\rule','\markboth',
670 '\setlength','\addtolength','\settodepth','\settoheight','\settowidth','\setcounter',
671 '\addtocontents','\addtocounter',
672 '\fontsize');
673 add_keys_to_hash(\%TeXmacro,3,'\addcontentsline');
674 add_keys_to_hash(\%TeXmacro,6,'\DeclareFontShape');
675 add_keys_to_hash(\%TeXmacro,['[','text','ignore'],
676 '\cite','\nocite','\citep','\citet','\citeauthor','\citeyear','\citeyearpar',
677 '\citealp','\citealt','\Citep','\Citet','\Citealp','\Citealt','\Citeauthor');
678 add_keys_to_hash(\%TeXmacro,['ignore','text'],'\parbox','\raisebox');
679 add_keys_to_hash(\%TeXmacro,['otherword'],'\marginpar','\footnote','\footnotetext');
680 add_keys_to_hash(\%TeXmacro,['header'],
681 '\title','\part','\chapter','\section','\subsection','\subsubsection','\paragraph','\subparagraph');
682 add_keys_to_hash(\%TeXmacro,['xxx','xxx','text'],'\multicolumn');
683 add_keys_to_hash(\%TeXmacro,['xxx','xxx'],'\newcommand','\renewcommand');
684 add_keys_to_hash(\%TeXmacro,['xxx','xxx','xxx'],'\newenvironment','\renewenvironment');
685
686 ### Environments
687 # The %TeXenvir hash provides content parsing rules (parser states).
688 # Environments that are not defined will be counted as the surrounding text.
689 #
690 # Parameters taken by the \begin{environment} are defined in %TeXmacro.
691 #
692 # Note that some environments may only exist within math-mode, and
693 # therefore need not be defined here: in fact, they should not as it
694 # is not clear if they will be in inlined or displayed math.
695 my %TeXenvir;
696 add_keys_to_hash(\%TeXenvir,'ignore',
697 'titlepage','tabbing','tabular','tabular*','thebibliography','lrbox');
698 add_keys_to_hash(\%TeXenvir,'text',
699 'document','letter','center','flushleft','flushright',
700 'abstract','quote','quotation','verse','minipage',
701 'description','enumerate','itemize','list',
702 'theorem','thm','lemma','definition','corollary','example','proof','pf');
703 add_keys_to_hash(\%TeXenvir,'inlinemath',
704 'math');
705 add_keys_to_hash(\%TeXenvir,'displaymath',
706 'displaymath','equation','equation*','eqnarray','eqnarray*','align','align*',);
707 add_keys_to_hash(\%TeXenvir,'float',
708 'float','picture','figure','figure*','table','table*');
709 add_keys_to_hash(\%TeXenvir,'xall',
710 'verbatim','tikzpicture');
711
712 # Environment parameters
713 my $PREFIX_ENVIR='begin'; # Prefix used for environment names
714 add_keys_to_hash(\%TeXmacro,1,
715 'beginthebibliography','beginlrbox','beginminipage');
716 add_keys_to_hash(\%TeXmacro,2,
717 'beginlist');
718 add_keys_to_hash(\%TeXmacro,['ignore'],
719 'beginletter');
720 add_keys_to_hash(\%TeXmacro,['xxx'],
721 'begintabular');
722 add_keys_to_hash(\%TeXmacro,['ignore','xxx'],
723 'begintabular*');
724 add_keys_to_hash(\%TeXmacro,['[','text'],
725 'begintheorem','beginthm','beginlemma','begindefinition','begincorollary','beginexample','beginproof','beginpf');
726 add_keys_to_hash(\%TeXmacro,['nooptions'],
727 'beginverbatim');
728
729 ### Macros that should be counted as one or more words
730 # Macros that represent text may be declared here. The value gives
731 # the number of words the macro represents.
732 my %TeXmacrocount=('\LaTeX'=>1,'\TeX'=>1,'beginabstract'=>['header','headerword']);
733
734 ### Macros for including tex files
735 # Allows \macro{file} to include file; or \macro file if of type 'input'.
736 # Main types are 'input' for \input, 'texfile' which adds '.tex', and
737 # 'file' which adds '.tex' if missing.
738 my %TeXfileinclude=('\input'=>'input','\include'=>'texfile');
739
740 ### Convert state keys to codes
741 convert_hash(\%TeXpreamble,\&keyarray_to_state);
742 convert_hash(\%TeXpackageinc,\&keyarray_to_state);
743 convert_hash(\%TeXfloatinc,\&keyarray_to_state);
744 convert_hash(\%TeXmacro,\&keyarray_to_state);
745 convert_hash(\%TeXmacrocount,\&keyarray_to_cnt);
746 convert_hash(\%TeXenvir,\&key_to_state);
747
748
749 ###### Define package specific rules
750
751 ### Package rule definitions
752
753 my %PackageTeXpreamble=(); # TeXpreamble definitions per package
754 my %PackageTeXpackageinc=(); # TeXpackageinc definitions per package
755 my %PackageTeXfloatinc=(); # TeXfloatinc definitions per package
756 my %PackageTeXmacro=(); # TeXmacro definitions per package
757 my %PackageTeXmacrocount=(); # TeXmacrocount definitions per package
758 my %PackageTeXenvir=(); # TeXenvir definitions per package
759 my %PackageTeXfileinclude=(); # TeXfileinclude definitions per package
760 my %PackageSubpackage=(); # Subpackages to include (listed in array [...])
761
762
763 # Rules for bibliography inclusion
764 $PackageTeXmacrocount{'%incbib'}={'beginthebibliography'=>['header','hword']};
765 $PackageTeXmacro{'%incbib'}={'\bibliography'=>1};
766 $PackageTeXenvir{'%incbib'}={'thebibliography'=>'text'};
767 $PackageTeXfileinclude{'%incbib'}={'\bibliography'=>'<bbl>'};
768
769 # Rules for package alltt
770 $PackageTeXenvir{'alltt'}={
771 'alltt'=>'xall'};
772
773 # Rules for package babel
774 # NB: Only core macros implemented, those expected found in regular documents
775 $PackageTeXenvir{'babel'}={
776 'otherlanguage'=>'text','otherlanguage*'=>'text'};
777 $PackageTeXmacro{'babel'}={
778 '\selectlanguage'=>1,'\foreignlanguage'=>['ignore','text'],
779 'beginotherlanguage'=>1,'beginotherlanguage*'=>1};
780
781 # Rules for package comment
782 $PackageTeXenvir{'comment'}={
783 'comment'=>'xxx'};
784
785 # Rules for package color
786 $PackageTeXmacro{'color'}={
787 '\textcolor'=>['ignore','text'],'\color'=>1,'\pagecolor'=>1,'\normalcolor'=>0,
788 '\colorbox'=>['ignore','text'],'\fcolorbox'=>['ignore','ignore','text'],
789 '\definecolor'=>3,\'DefineNamedColor'=>4};
790
791 # Rules for package endnotes
792 $PackageTeXmacro{'endnotes'}={'\endnote'=>['oword'],'\endnotetext'=>['oword'],'\addtoendnotetext'=>['oword']};
793
794 # Rules for package etoolbox
795 $PackageTeXmacro{'etoolbox'}={'\apptocmd'=>['xxx','ignore','ignore','ignore'],
796 '\pretocmd'=>['xxx','ignore','ignore','ignore'],
797 '\patchcmd'=>['xxx','xxx','xxx','ignore','ignore']};
798
799 # Rules for package fancyhdr
800 $PackageTeXmacro{'fancyhdr'}={
801 '\fancyhf'=>1,'\lhead'=>1,'\chead'=>1,'\rhead'=>1,'\lfoot'=>1,'\cfoot'=>1,'\rfoot'=>1};
802
803 # Rules for package geometry
804 $PackageTeXmacro{'geometry'}={
805 '\geometry'=>1,'\newgeometry'=>1,'\restoregeometry'=>0,,'\savegeometry'=>1,'\loadgeometry'=>1};
806
807 # Rules for package graphicx
808 $PackageTeXmacro{'graphicx'}={
809 '\DeclareGraphicsExtensions'=>1,'\graphicspath'=>1,
810 '\includegraphics'=>['[','ignore','ignore'],
811 '\includegraphics*'=>['[','ignore','[','ignore','[','ignore','ignore'],
812 '\rotatebox'=>1,'\scalebox'=>1,'\reflectbox'=>1,'\resizebox'=>1};
813
814 # Rules for package hyperref (urls themselves counted as one word)
815 # NB: \hyperref[label]{text} preferred over \hyperref{url}{category}{name}{text}
816 # NB: Macros for use in Form environments not implemented
817 $PackageTeXmacro{'hyperref'}={
818 '\hyperref'=>['[','ignore','text'],
819 '\url'=>1,'\nolinkurl'=>1,'\href'=>['ignore','text'],
820 '\hyperlink'=>['ignore','text'],'\hypertarget'=>['ignore','text'],
821 '\hyperbaseurl'=>1,'\hyperimage'=>['ignore','text'],'\hyperdef'=>['ignore','ignore','text'],
822 '\phantomsection'=>0,'\autoref'=>1,'\autopageref'=>1,
823 '\hypersetup'=>1,'\urlstyle'=>1,
824 '\pdfbookmark'=>2,'\currentpdfbookmark'=>2,'\subpdfbookmark'=>2,'\belowpdfbookmark'=>2,
825 '\pdfstringref'=>2,'\texorpdfstring'=>['text','ignore'],
826 '\hypercalcbp'=>1,'\Acrobatmenu'=>2};
827 $PackageTeXmacrocount{'hyperref'}={
828 '\url'=>1,'\nolinkurl'=>1};
829
830 # Rules for package import
831 $PackageTeXfileinclude{'import'}={
832 '\import'=>'dir file','\subimport'=>'subdir file',
833 '\inputfrom'=>'dir file','\subinputfrom'=>'subdir file',
834 '\includefrom'=>'dir file','\subincludefrom'=>'subdir file'};
835
836 # Rules for package inputenc
837 $PackageTeXmacro{'inputenc'}={
838 '\inputencoding'=>1};
839
840 # Rules for package listings
841 $PackageTeXenvir{'listings'}={'lstlisting'=>'xall'};
842 $PackageTeXmacro{'listings'}={'\lstset'=>['ignore'],'\lstinputlisting'=>['ignore']};
843
844 # Rules for package psfig
845 $PackageTeXmacro{'psfig'}={'\psfig'=>1};
846
847 # Rules for package sectsty
848 $PackageTeXmacro{'sectsty'}={
849 '\allsectionsfont'=>1,'\partfont'=>1,'\chapterfont'=>1,'\sectionfont'=>1,
850 '\subsectionfont'=>1,'\subsubsectionfont'=>1,'\paragraphfont'=>1,'\subparagraphfont'=>1,
851 '\minisecfont'=>1,'\partnumberfont'=>1,'\parttitlefont'=>1,'\chapternumberfont'=>1,
852 '\chaptertitlefont'=>1,'\nohang'=>0};
853
854 # Rules for package setspace
855 $PackageTeXenvir{'setspace'}={
856 'singlespace'=>'text','singlespace*'=>'text','onehalfspace'=>'text','doublespace'=>'text',
857 'spacing'=>'text'};
858 $PackageTeXmacro{'setspace'}={
859 'beginspacing'=>1,
860 '\singlespacing'=>0,'\onehalfspacing'=>0,'\doublespacing'=>0,
861 '\setstretch'=>1,'\SetSinglespace'=>1};
862
863 # Rules for package subfiles
864 $PackageTeXfileinclude{'subfiles'}={
865 '\subfile'=>'file'};
866
867 # Rules for package url
868 # NB: \url|...| variant not implemented, only \url{...}
869 # NB: \urldef{macro}{url} will not be counted
870 $PackageTeXmacro{'url'}={
871 '\url'=>1,'\urldef'=>2,'\urlstyle'=>1,'\DeclareUrlCommand'=>['ignore','xxx']};
872 $PackageTeXmacro{'setspace'}={
873 '\url'=>1};
874
875 # Rules for package wrapfig
876 $PackageTeXenvir{'wrapfig'}={
877 'wrapfigure'=>'float','wraptable'=>'float'};
878 $PackageTeXmacro{'wrapfig'}={
879 'beginwrapfigure'=>2,'beginwraptable'=>2};
880
881 # Rules for package xcolor (reimplements the color package)
882 # NB: only main macros (mostly from package color) included
883 $PackageTeXmacro{'xcolor'}={
884 '\textcolor'=>['ignore','text'],'\color'=>1,'\pagecolor'=>1,'\normalcolor'=>0,
885 '\colorbox'=>['ignore','text'],'\fcolorbox'=>['ignore','ignore','text'],
886 '\definecolor'=>3,\'DefineNamedColor'=>4,
887 '\colorlet'=>2};
888
889 # Rules for package xparse
890 $PackageSubpackage{'xparse'}=['etoolbox'];
891
892
893 ###### Main script
894
895
896
897 ###################################################
898
899 MAIN(@ARGV);
900 exit; # Just to make sure it ends here...
901
902 ###################################################
903
904
905 #########
906 ######### Main routines
907 #########
908
909 # MAIN ROUTINE: Handle arguments, then parse files
910 sub MAIN {
911 my @args;
912 push @args,@StartupOptions;
913 push @args,@_;
914 Initialise();
915 Check_Arguments(@args);
916 my @toplevelfiles=Parse_Arguments(@args);
917 Apply_Options();
918 if (scalar @toplevelfiles>0 || $fileFromSTDIN) {
919 if ($showVersion && !$htmlstyle && !($briefsum && $totalflag)) {
920 print "\n=== LaTeX word count (TeXcount version $versionnumber) ===\n\n";
921 }
922 conditional_print_style_list();
923 my $totalcount=Parse_file_list(@toplevelfiles);
924 conditional_print_total($totalcount);
925 Report_Errors();
926 if ($optionWordFreq || $optionWordClassFreq) {print_word_freq();}
927 if ($optionMacroStat) {print_macro_stat();}
928 } elsif ($showcodes>1) {
929 conditional_print_style_list();
930 } else {
931 error($Main,'No files specified.');
932 }
933 Close_Output();
934 }
935
936 # Initialise, overrule initial settings, etc.
937 sub Initialise {
938 _option_subcount();
939 # Windows settings
940 if ($^O eq 'MSWin32') {
941 } elsif ($^O=~/^MSWin/) {
942 #DELETE: do not overrule colour setting
943 option_ansi_colours(0);
944 }
945 }
946
947 # Check arguments, exit on exit condition
948 sub Check_Arguments {
949 my @args=@_;
950 if (!@args) {
951 print_version();
952 print_help();
953 exit;
954 }
955 for my $arg (@args) {
956 $arg=~s/^(--?(h|\?|help)|\/(\?|h))\b/-h/;
957 $arg=~s/[=:]/=/;
958 if ($arg=~/^-h$/) {
959 print_help();
960 exit;
961 } elsif ($arg=~/^-(h-)?(man|manual)$/) {
962 print_help_man();
963 exit;
964 } elsif ($arg=~/^-h-?(opt|options?)$/) {
965 print_help_options();
966 exit;
967 } elsif ($arg=~/^-h-?(opt|options?)=(.*)$/) {
968 print_help_options_subset($2);
969 exit;
970 } elsif ($arg=~/^-h(-rule)?=(.*)$/) {
971 print_help_on_rule($2);
972 exit;
973 } elsif ($arg=~/^-h-styles?$/) {
974 print_help_on_styles();
975 exit;
976 } elsif ($arg=~/^-h-styles?=(\w+)$/) {
977 print_help_on_styles($1);
978 exit;
979 } elsif ($arg=~/^-h-(tc|(tc)?inst(ructions?))?$/) {
980 print_help_tcinst();
981 exit;
982 } elsif ($arg=~/^--?(ver|version)$/) {
983 print_version();
984 exit;
985 } elsif ($arg=~/^--?(lic|license|licence)$/) {
986 print_license();
987 exit;
988 }
989 }
990 return 1;
991 }
992
993 # Parse arguments, set options (global) and return file list
994 sub Parse_Arguments {
995 my @args=@_;
996 my @files;
997 foreach my $arg (@args) {
998 if ($arg=~/^\-/) {
999 $arg=~s/[=:]/=/;
1000 if (parse_option($arg)) {next;}
1001 print "Invalid option $arg \n\n";
1002 print_help();
1003 exit;
1004 } elsif ($arg=~/^@\-/) { # ignored option
1005 next;
1006 }
1007 $arg=~s/\\/\//g;
1008 push @files,$arg;
1009 }
1010 return @files;
1011 }
1012
1013 # Parse individual option parameters
1014 sub parse_option {
1015 my $arg=shift @_;
1016 return parse_options_preset($arg)
1017 || parse_options_parsing($arg)
1018 || parse_options_counts($arg)
1019 || parse_options_output($arg)
1020 || parse_options_format($arg)
1021 ;
1022 }
1023
1024 # Parse presetting options
1025 sub parse_options_preset {
1026 my $arg=shift @_;
1027 if ($arg=~/^-(opt|option|options|optionfile)=(.*)$/) {
1028 _parse_optionfile($2);
1029 }
1030 else {return 0;}
1031 return 1;
1032 }
1033
1034 # Parse parsing options
1035 sub parse_options_parsing {
1036 my $arg=shift @_;
1037 if ($arg eq '-') {$fileFromSTDIN=1;}
1038 elsif ($arg eq '-merge') {$includeTeX=$INCLUDE_MERGE;}
1039 elsif ($arg eq '-inc') {$includeTeX=$INCLUDE_AFTER;}
1040 elsif ($arg eq '-noinc') {$includeTeX=$INCLUDE_NONE;}
1041 elsif ($arg =~/^-(includepackage|incpackage|package|pack)=(.*)$/) {include_package($2);}
1042 elsif ($arg eq '-incbib') {$includeBibliography=1;}
1043 elsif ($arg eq '-nobib') {$includeBibliography=0;}
1044 elsif ($arg eq '-dir') {$globalworkdir=undef;}
1045 elsif ($arg=~/^-dir=(.*)$/) {
1046 $globalworkdir=$1;
1047 $globalworkdir=~s:([^\/\\])$:$1\/:;
1048 }
1049 elsif ($arg eq '-auxdir') {$auxdir=undef;}
1050 elsif ($arg=~/^-auxdir=(.*)$/) {
1051 $auxdir=$1;
1052 $auxdir=~s:([^\/\\])$:$1\/:;
1053 }
1054 elsif ($arg =~/^-(enc|encode|encoding)=(.+)$/) {$encoding=$2;}
1055 elsif ($arg =~/^-(utf8|unicode)$/) {$encoding='utf8';}
1056 elsif ($arg =~/^-(alpha(bets?)?)=(.*)$/) {set_script_options(\@AlphabetScripts,$3);}
1057 elsif ($arg =~/^-(logo(grams?)?)=(.*)$/) {set_script_options(\@LogogramScripts,$3);}
1058 elsif ($arg =~/^-([-a-z]+)$/ && set_language_option($1)) {}
1059 elsif ($arg eq '-relaxed') {
1060 $MacroOptionPattern=$NamedMacroOptionPattern{'relaxed'};
1061 $LetterPattern=$NamedLetterPattern{'relaxed'};
1062 }
1063 elsif ($arg eq '-restricted') {
1064 $MacroOptionPattern=$NamedMacroOptionPattern{'restricted'};
1065 $LetterPattern=$NamedLetterPattern{'restricted'};
1066 }
1067 else {return 0;}
1068 return 1;
1069 }
1070
1071 # Parse count and summation options
1072 sub parse_options_counts {
1073 my $arg=shift @_;
1074 if ($arg =~/^-sum(=(.+))?$/) {_option_sum($2);}
1075 elsif ($arg =~/^-nosum/) {@sumweights=();}
1076 elsif ($arg =~/^-(sub|subcounts?)(=(.+))?$/) {_option_subcount($3);}
1077 elsif ($arg =~/^-(nosub|nosubcounts?)/) {$showsubcounts=0;}
1078 elsif ($arg eq '-freq') {$optionWordFreq=1;}
1079 elsif ($arg =~/^-freq=(\d+)$/) {$optionWordFreq=$1;}
1080 elsif ($arg eq '-stat') {$optionWordClassFreq=1;}
1081 elsif ($arg =~/^-macro-?(stat|freq)$/) {$optionMacroStat=1;}
1082 else {return 0;}
1083 return 1;
1084 }
1085
1086 # Apply sum option
1087 sub _option_sum {
1088 my $arg=shift @_;
1089 if (!defined $arg) {
1090 @sumweights=(0,1,1,1,0,0,1,1);
1091 } elsif ($arg=~/^(\d+(\.\d*)?([,+]\d+(\.\d*)?){0,6})$/) {
1092 @sumweights=(0,split(/[,+]/,$arg));
1093 print STDERR "SUMWEIGHTS: ",join(', ',@sumweights),"\n";
1094 } else {
1095 print STDERR "Warning: Option value $arg not valid, ignoring option.\n";
1096 }
1097 }
1098
1099 # Apply subcount options
1100 sub _option_subcount {
1101 my $arg=shift @_;
1102 $showsubcounts=2;
1103 if (!defined $arg) {
1104 %BreakPoints=%{$BreakPointsOptions{'default'}};
1105 } elsif (my $option=$BreakPointsOptions{$arg}) {
1106 %BreakPoints=%{$option};
1107 } else {
1108 print STDERR "Warning: Option value $arg not valid, using default instead.\n";
1109 %BreakPoints=%{$BreakPointsOptions{'default'}};
1110 }
1111 }
1112
1113 # Parse output and verbosity options
1114 sub parse_options_output {
1115 my $arg=shift @_;
1116 if ($arg eq '-strict') {$strictness=1;}
1117 elsif ($arg eq '-v') {set_verbosity_options('3');}
1118 elsif ($arg =~/^-v([0-4=+\-].*)/) {set_verbosity_options($1);}
1119 elsif ($arg =~/^-showstates?$/ ) {$showstates=1;}
1120 elsif ($arg =~/^-(q|quiet)$/ ) {$printlevel=-1;}
1121 elsif ($arg =~/^-(template)=(.*)$/ ) {_set_output_template($2);}
1122 elsif ($arg eq '-split') {$optionFast=1;}
1123 elsif ($arg eq '-nosplit') {$optionFast=0;}
1124 elsif ($arg eq '-showver') {$showVersion=1;}
1125 elsif ($arg eq '-nover') {$showVersion=-1;}
1126 elsif ($arg =~/^-nosep(arator)?s?$/ ) {$separator='';}
1127 elsif ($arg =~/^-sep(arator)?s?=(.*)$/ ) {$separator=$2;}
1128 elsif ($arg =~/^-out=(.*)/ ) {
1129 close STDOUT;
1130 open STDOUT,'>',$1 or die "Could not open out file for writing: $1";
1131 }
1132 elsif ($arg =~/^-out-stderr/ ) {select STDERR;}
1133 else {return 0;}
1134 return 1;
1135 }
1136
1137 # Set output template
1138 sub _set_output_template {
1139 my $template=shift @_;
1140 $outputtemplate=$template;
1141 if ($template=~/\{(SUM)[\?\}]/i && !@sumweights) {
1142 @sumweights=(0,1,1,1,0,0,1,1);
1143 }
1144 if ($template=~/\{SUB\?/i && !$showsubcounts) {
1145 _option_subcount();
1146 }
1147 }
1148
1149 # Parse output formating options
1150 sub parse_options_format {
1151 my $arg=shift @_;
1152 if ($arg eq '-brief') {$briefsum=1;}
1153 elsif ($arg eq '-total') {$totalflag=1;}
1154 elsif ($arg eq '-0') {$briefsum=1;$totalflag=1;$printlevel=-1;$finalLineBreak=0;}
1155 elsif ($arg eq '-1') {$briefsum=1;$totalflag=1;$printlevel=-1;}
1156 elsif ($arg eq '-htmlcore' ) {option_ansi_colours(0);$htmlstyle=$HTML_CORE;}
1157 elsif ($arg eq '-html' ) {option_ansi_colours(0);$htmlstyle=$HTML_FULL;}
1158 elsif ($arg eq '-tex' ) {option_ansi_colours(0);$texcodeoutput=1;}
1159 elsif ($arg =~/^\-(nocol|nc$)/) {option_ansi_colours(0);}
1160 elsif ($arg =~/^\-(col)$/) {option_ansi_colours(1);}
1161 elsif ($arg eq '-codes') {$showcodes=2;}
1162 elsif ($arg eq '-nocodes') {$showcodes=0;}
1163 elsif ($arg =~/^-htmlfile=(.+)$/) {$HTMLfile=$1;}
1164 elsif ($arg =~/^-cssfile=(.+)$/) {$CSSfile=$1;}
1165 elsif ($arg =~/^-css=file:(.+)$/) {$CSSfile=$1;}
1166 elsif ($arg =~/^-css=(.+)$/) {$CSShref=$1;}
1167 else {return 0;}
1168 return 1;
1169 }
1170
1171 # Include options from option file
1172 sub _parse_optionfile {
1173 my $filename=shift @_;
1174 open(FH,'<',$filename)
1175 || die "Option file not found: $filename\n";
1176 my @options=<FH>;
1177 close(FH);
1178 s/^\s*(#.*|)//s for @options;
1179 my $text=join('',@options);
1180 $text=~s/(\n|\r|\r\n)\s*\\//g;
1181 @options=split("\n",$text);
1182 foreach my $arg (@options) {
1183 __optionfile_tc($arg)
1184 || parse_option($arg)
1185 || die "Invalid option $arg in $filename.\n";
1186 }
1187 }
1188
1189 # Parse option file TC options
1190 sub __optionfile_tc {
1191 my $arg=shift @_;
1192 if ($arg=~/^\%\%/) {return 1;}
1193 $arg=~s/^\%\s*// || return 0;
1194 if ($arg=~/^subst\s+(\\\w+)\s+(.*)$/i) {
1195 $substitutions{$1}=$2;
1196 } elsif ($arg=~/^(\w+)\s+([\\]*\w+)\s+([^\s\n]+)(\s+(\-?[0-9]+|\w+))?/i) {
1197 tc_macro_param_option($Main,$1,$2,$3,$5) || die "Invalid TC option: $arg\n";
1198 } else {
1199 print "Invalid TC option format: $arg\n";
1200 return 0;
1201 }
1202 return 1;
1203 }
1204
1205 # Parse file list and return total count
1206 sub Parse_file_list {
1207 my @files=@_;
1208 my $listtotalcount=new_count('Total');
1209 foreach (@files) {
1210 $_='"'.$_.'"'
1211 }
1212 if (@files) {
1213 @files=<@files>; # For the sake of Windows: expand wildcards!
1214 for my $file (@files) {
1215 my $filetotalcount=parse_file($file);
1216 add_to_total($listtotalcount,$filetotalcount);
1217 }
1218 }
1219 if ($fileFromSTDIN) {
1220 my $filetotalcount=parse_file($_STDIN_);
1221 add_to_total($listtotalcount,$filetotalcount);
1222 }
1223 return $listtotalcount;
1224 }
1225
1226 # Parse file and included files, and return total count
1227 sub parse_file {
1228 my $file=shift @_;
1229 if (defined ($workdir=$globalworkdir)) {}
1230 elsif ($file eq $_STDIN_) {$workdir='';}
1231 else {
1232 $workdir=$file;
1233 $workdir =~ s/^((.*[\\\/])?)[^\\\/]+$/$1/;
1234 }
1235 if ($htmlstyle && ($printlevel>0 || !$totalflag)) {print "\n<div class='filegroup'>\n";}
1236 my $filetotalcount=new_count('File(s) total: '.$file);
1237 @filelist=();
1238 _add_file($filetotalcount,[$file,$workdir],'File: '.$file);
1239 foreach my $f (@filelist) {
1240 _add_file($filetotalcount,$f,'Included file: '.$f->[0]);
1241 }
1242 if (!$totalflag && get_count($filetotalcount,$CNT_FILE)>1) {
1243 #if ($htmlstyle) {formatprint("Sum of files: $file\n",'h2');}
1244 print_count($filetotalcount,'sumcount',"Sum of files: $file");
1245 }
1246 if ($htmlstyle && ($printlevel>0 || !$totalflag)) {print "</div>\n\n";}
1247 return $filetotalcount;
1248 }
1249
1250 # Parse single file, included files will be appended to @filelist.
1251 sub _add_file {
1252 my ($filetotalcount,$pathfile,$title)=@_;
1253 my @paths=@$pathfile;
1254 my $file=shift @paths;
1255 my $tex=TeXfile($file,$title);
1256 if (!defined $tex) {
1257 error($Main,'File not found or not readable: '.$file);
1258 return;
1259 }
1260 $tex->{'PATH'}=\@paths;
1261 parse($tex);
1262 my $filecount=next_subcount($tex);
1263 if (!$totalflag) {print_count($filecount);}
1264 add_to_total($filetotalcount,$filecount);
1265 }
1266
1267
1268 ######
1269 ###### Subroutines
1270 ######
1271
1272 ###### CMD specific implementations
1273
1274
1275 # Add file to list of files scheduled for parsing
1276 sub include_file {
1277 my ($tex,$state,$file,$refparam)=@_;
1278 my %params=%$refparam;
1279 my $type=$params{'<type>'};
1280 my @paths=@{$tex->{'PATH'}};
1281 if ($type eq '<bbl>' && defined $auxdir) {
1282 $auxdir=~s/([\\\/])*$/\//;
1283 if (defined $globalworkdir) {@paths=[$auxdir];}
1284 elsif ($auxdir=~/^(\w:)?[\\\/]/) {@paths=[$auxdir];}
1285 else {@paths=[$workdir.$auxdir]}
1286 }
1287 foreach my $key (split(/\s+/,$type)) {
1288 my $value=$params{$key};
1289 if ($key eq 'dir') {unshift @paths,$workdir.$value;}
1290 elsif ($key eq 'subdir') {unshift @paths,$paths[0].$value;}
1291 }
1292 # Decide full file path
1293 my $filepath;
1294 if ($file=~/^(\w:)?[\\\/]/) {$filepath=$file;}
1295 else {
1296 $filepath=_find_file_in_path($tex,$file,\@paths,$params{'SUFFICES'}) || BLOCK {
1297 error($tex,'File '.$file.' not found in path ['.join(';',@paths).'].');
1298 return;
1299 };
1300 }
1301 if ($includeTeX==$INCLUDE_MERGE) {
1302 my $bincode=read_binary($filepath) || BLOCK {
1303 error($tex,"File $filepath not readable.");
1304 return;
1305 };
1306 flush_next($tex);
1307 line_return(0,$tex);
1308 my $texstate=texcode_insert_text($tex,$bincode,$filepath,@paths);
1309 parse_all($tex,$state);
1310 texcode_restore_state($tex,$texstate);
1311 } else {
1312 push @filelist,[$filepath,@paths];
1313 }
1314 }
1315
1316 # Seach path list to find file
1317 sub _find_file_in_path {
1318 my ($tex,$file,$paths,$suffices)=@_;
1319 foreach my $suffix (@{$suffices}) {
1320 foreach my $path (@{$paths}) {
1321 if ($path && $path!~/[\\\/]$/) {$path.='/';}
1322 my $filepath=$path.$file.$suffix;
1323 if (-e $filepath && ! -d $filepath) {return $filepath;}
1324 # DELETE: elsif ($filepath=~/\.tex$/i) {}
1325 # DELETE: elsif (-e $filepath.'.tex') {return $filepath.'.tex';}
1326 }
1327 }
1328 return undef;
1329 }
1330
1331 # Print count (total) if conditions are met
1332 sub conditional_print_total {
1333 my $sumcount=shift @_;
1334 if ($totalflag || number_of_subcounts($sumcount)>1) {
1335 if ($totalflag && $briefsum && @sumweights) {
1336 print get_sum_count($sumcount),"\n";
1337 } elsif ($htmlstyle) {
1338 print "<div class='sumgroup'>\n";
1339 formatprint('Total word count','h2');
1340 print_count($sumcount,'sumcount');
1341 print "</div>\n";
1342 } else {
1343 print_count($sumcount,'sumcount');
1344 }
1345 }
1346 }
1347
1348 # Set or unset use of ANSI colours
1349 sub option_ansi_colours {
1350 my $flag=shift @_;
1351 $ENV{'ANSI_COLORS_DISABLED'} = $flag?undef:1;
1352 }
1353
1354 # Print text using ANSI colours
1355 sub ansiprint {
1356 my ($text,$colour)=@_;
1357 print Term::ANSIColor::colored($text,$colour);
1358 }
1359
1360
1361 ###### Option handling
1362
1363
1364 # Apply options to set values
1365 sub Apply_Options {
1366 apply_encoding_options();
1367 if ($htmlstyle==$HTML_FULL) {html_head();}
1368 flush_errorbuffer($Main);
1369 apply_language_options();
1370 if ($includeBibliography) {apply_include_bibliography();}
1371 if ($showcodes>1 && !($STYLE{'<printlevel>'})) {%STYLE=%{$STYLES{'All'}};}
1372 if ($showstates) {set_verbosity_options('+States');}
1373 if (!@sumweights) {set_verbosity_options('-Sums');}
1374 (defined $printlevel)
1375 || (defined ($printlevel=$STYLE{'<printlevel>'}))
1376 || ($printlevel=$defaultprintlevel);
1377 }
1378
1379 # Set or add styles included in the verbose output
1380 sub set_verbosity_options {
1381 my $verb=shift @_;
1382 my $st;
1383 if ($defaultprintlevel<1) {$defaultprintlevel=1;}
1384 if ( $verb=~s/^([0-4])// || $verb=~s/^=([0-4])?// ) {
1385 my $key=$1;
1386 if (!defined $key) {%STYLE=(%{$STYLES{'<core>'}});}
1387 elsif ($st=$STYLES{$key}) {%STYLE=(%$st);}
1388 else {
1389 error($Main,"Unknown verbosity option '$key'.");
1390 %STYLE=(%{$STYLES{'<core>'}});
1391 }
1392 }
1393 while ($verb=~s/^([\+\-]?)(\w+)//) {
1394 my $add=!($1 eq '-');
1395 my $key=$2;
1396 if ($st=$STYLES{$key}) {
1397 if ($add) {@STYLE{keys %$st}=values %$st;}
1398 else {delete @STYLE{keys %$st};}
1399 } elsif ($st=$STYLES{'All'}->{$key}) {
1400 if ($add) {$STYLE{$key}=$st;}
1401 elsif ($STYLE{$key}) {delete $STYLE{$key};}
1402 } else {
1403 error($Main,"Unknown verbosity option '$key'.");
1404 }
1405 }
1406 if ($verb ne '') {
1407 error($Main,"Unknown verbosity option format: $verb");
1408 }
1409 }
1410
1411 # Set or add scripts to array of scripts
1412 sub set_script_options {
1413 my ($scriptset,$str)=@_;
1414 if ($str=~s/^\+//) {} else {splice(@$scriptset,0,scalar $scriptset);}
1415 my @scripts=split(/[+,]/,$str);
1416 foreach my $scr (@scripts) {
1417 $scr=~tr/_/ /;
1418 if ($scr eq 'Alphabetic') {
1419 warning($Main,'Using alphabetic instead of Unicode class Alphabetic');
1420 $scr='alphabetic';
1421 }
1422 if ($scr=~/^[a-z]/) {$scr='Is_'.$scr;}
1423 if (_is_property_valid($scr)) {push @$scriptset,$scr;}
1424 else {error($Main,"Unknown script $scr ignored.");}
1425 }
1426 }
1427
1428 sub _is_property_valid {
1429 my $script=shift @_;
1430 if (! $script=~/^\w+$/) {return 0;}
1431 eval {' '=~/\p{$script}/};
1432 if ($@) {return 0;} else {return 1;}
1433 }
1434
1435 # Set language option, return language if applied, undef if not
1436 sub set_language_option {
1437 my $language=shift @_;
1438 if ($language=~/^(count\-?)all$/) {
1439 @AlphabetScripts=qw/Digit Is_alphabetic/;
1440 @LogogramScripts=qw/Ideographic Katakana Hiragana Thai Lao Hangul/;
1441 } elsif ($language=~/^words(-?only)?$/) {
1442 @LogogramScripts=();
1443 } elsif ($language=~/^(ch|chinese|zhongwen)(-?only)?$/) {
1444 @LogogramScripts=qw/Han/;
1445 if (defined $2) {$LetterPattern=undef;}
1446 @encodingGuessOrder=@{$NamedEncodingGuessOrder{'chinese'}};
1447 return 'chinese';
1448 } elsif ($language=~/^(jp|japanese)(-?only)?$/) {
1449 @LogogramScripts=qw/Han Hiragana Katakana/;
1450 if (defined $2) {$LetterPattern=undef;}
1451 @encodingGuessOrder=@{$NamedEncodingGuessOrder{'japanese'}};
1452 return 'japanese';
1453 } elsif ($language=~/^(kr|korean)(-?only)?$/) {
1454 @LogogramScripts=qw/Han Hangul/;
1455 if (defined $2) {$LetterPattern=undef;}
1456 @encodingGuessOrder=@{$NamedEncodingGuessOrder{'korean'}};
1457 return 'korean';
1458 } elsif ($language=~/^(kr|korean)-?words?(-?only)?$/) {
1459 if (defined $2) {
1460 @AlphabetScripts=qw/Hangul/;
1461 @LogogramScripts=qw/Han/;
1462 } else {
1463 @AlphabetScripts=qw/Digit Is_alphabetic Hangul/;
1464 @LogogramScripts=qw/Han Katakana Hiragana Thai Lao/;
1465 }
1466 @encodingGuessOrder=@{$NamedEncodingGuessOrder{'korean'}};
1467 return 'korean-words';
1468 } elsif ($language=~/^(char|character|letter)s?(-?only)?$/) {
1469 @WordPatterns=($NamedWordPattern{'letters'});
1470 if (defined $2) {@LogogramScripts=();}
1471 $countdesc[1]='Letters in text';
1472 $countdesc[2]='Letters in headers';
1473 $countdesc[3]='Letters in captions';
1474 return 'letter';
1475 } elsif ($language=~/^all-nonspace-(char|character|letter)s?$/) {
1476 @WordPatterns=($NamedWordPattern{'letters'});
1477 @AlphabetScripts=qw/Digit Is_alphabetic Is_punctuation/;
1478 $countdesc[1]='Characters in text';
1479 $countdesc[2]='Characters in headers';
1480 $countdesc[3]='Characters in captions';
1481 return 'nonspace-characters';
1482 } else {
1483 return undef;
1484 }
1485 }
1486
1487 # Set encoding based on encoding options, guess encoding if not set
1488 sub apply_encoding_options {
1489 if (defined $encoding && $encoding eq 'guess') {$encoding=undef;}
1490 if (!defined $encoding) {
1491 } elsif (ref(find_encoding($encoding))) {
1492 if (!$htmlstyle) {$outputEncoding=$encoding;}
1493 } else {
1494 error($Main,"Unknown encoding $encoding ignored.");
1495 error_details($Main,'Valid encodings are: '.wrap('','',join(', ',Encode->encodings(':all'))));
1496 $encoding=undef;
1497 }
1498 if (!defined $outputEncoding) {$outputEncoding='utf8';}
1499 binmode STDIN;
1500 binmode STDOUT,':encoding('.$outputEncoding.')';
1501 }
1502
1503 # Apply language options
1504 sub apply_language_options {
1505 my @tmp;
1506 if (defined $LetterPattern && @AlphabetScripts && scalar @AlphabetScripts>0) {
1507 @tmp=@AlphabetScripts;
1508 foreach (@tmp) {$_='\\p{'.$_.'}';}
1509 my $letterchars='['.join('',@tmp).']';
1510 my $letter=$LetterPattern;
1511 $letter=~s/@/$letterchars/g;
1512 @WordPatterns=map { s/\@/$letter/g ; qr/$_/ } @WordPatterns;
1513 } else {
1514 @WordPatterns=();
1515 }
1516 if (@LogogramScripts && scalar @LogogramScripts>0) {
1517 @tmp=@LogogramScripts;
1518 foreach (@tmp) {$_='\\p{'.$_.'}';}
1519 push @WordPatterns,'['.join('',@tmp).']';
1520 }
1521 if (scalar @WordPatterns==0) {
1522 error($Main,'No script (alphabets or logograms) defined. Using fallback mode.');
1523 push @WordPatterns,'\\w+';
1524 }
1525 $WordPattern=join '|',@WordPatterns;
1526 }
1527
1528 # Apply incbib rule
1529 sub apply_include_bibliography {
1530 include_package('%incbib');
1531 }
1532
1533 # Process TC instruction, return 1 if applied, 0 if not (e.g. error)
1534 sub tc_macro_param_option {
1535 my ($tex,$instr,$macro,$param,$option)=@_;
1536 if (!defined $param) {
1537 error($tex,'%TC:'.$instr.' requires parameter rule specification.');
1538 return 0;
1539 }
1540 elsif ($instr eq 'macro') {
1541 if (!($macro=~/^\\/)) {
1542 warning($tex,'%TC:macro '.$macro.': should perhaps be \\'.$macro.'?');
1543 }
1544 return _tc_macro_set_param($tex,\%TeXmacro,$instr,$macro,$param);
1545 }
1546 elsif ($instr eq 'exclude') {
1547 warning($tex,'%TC:exclude is deprecated. Use %TC:macro instead.');
1548 return _tc_macro_set_param($tex,\%TeXmacro,$instr,$macro,$param);
1549 }
1550 elsif ($instr eq 'header') {
1551 warning($tex,'%TC:header is deprecated. Instead use e.g. %TC:macro \\name [header].');
1552 $TeXmacrocount{$macro}=[$CNT_COUNT_HEADER];
1553 return _tc_macro_set_param($tex,\%TeXmacro,$instr,$macro,$param);
1554 }
1555 elsif ($instr eq 'preambleinclude') {
1556 return _tc_macro_set_param($tex,\%TeXpreamble,$instr,$macro,$param);
1557 }
1558 elsif ($instr eq 'floatinclude') {
1559 return _tc_macro_set_param($tex,\%TeXfloatinc,$instr,$macro,$param);
1560 }
1561 elsif ($instr=~/^(group|envir)$/) {
1562 if (!defined $option) {
1563 error($tex,'TC:'.$instr.' requires contents rule specification.');
1564 return 0;
1565 }
1566 defined ($option=key_to_state($option,$tex)) || return 0;
1567 $TeXenvir{$macro}=$option;
1568 return _tc_macro_set_param($tex,\%TeXmacro,$instr,$PREFIX_ENVIR.$macro,$param);
1569 }
1570 elsif ($instr=~/^(macrocount|macroword)$/) {
1571 return _tc_macro_set_param($tex,\%TeXmacrocount,$instr,$macro,$param,\&key_to_cnt,$REGEX_NUMBER);
1572 }
1573 elsif ($instr eq 'fileinclude') {
1574 # No parameter checking here, just pass on; errors reported when used instead.
1575 $param=~s/^\[(.*)\]$/$1/;
1576 $param=~s/,/ /g;
1577 assert($param=~/^\w+(\s\w+)*$/,$tex,'Invalid %TC:fileinclude parameter: '.$param)
1578 || return 0;
1579 $TeXfileinclude{$macro}=$param;
1580 }
1581 elsif ($instr eq 'breakmacro') {$BreakPoints{$macro}=$param;}
1582 else {
1583 error($tex,'Unknown TC command: '.$instr);
1584 return 0;
1585 }
1586 return 1;
1587 }
1588
1589 # Convert TC command parameters and add to hash
1590 sub _tc_macro_set_param {
1591 my ($tex,$hash,$instr,$macro,$param,$keymap,$validregex)=@_;
1592 if (!defined $keymap) {$keymap=\&key_to_state; $validregex=$REGEX_NUMBER;}
1593 $param=__interpret_tc_parameter($tex,$param,$keymap,$validregex);
1594 if (!defined $param) {return 0;}
1595 $hash->{$macro}=$param;
1596 return 1;
1597 }
1598
1599 # Convert [...] into array of states, optionally return value if a valid pattern
1600 sub __interpret_tc_parameter {
1601 my ($tex,$param,$keymap,$validregex)=@_;
1602 if ((defined $validregex) && ($param=~$validregex)) {
1603 return $param;
1604 } elsif ($param=~/^\[([0-9a-zA-Z,:]*)\]$/) {
1605 my @params;
1606 my $value;
1607 foreach my $key (split(',',$1)) {
1608 if ($key=~/^(\w*):(\w+)$/) {
1609 defined ($value=$keymap->($PREFIX_PARAM_OPTION.$1,$tex)) || return undef;
1610 push @params,$value;
1611 $key=$2;
1612 }
1613 defined ($value=$keymap->($key,$tex)) || return undef;
1614 push @params,$value;
1615 }
1616 return [@params];
1617 }
1618 error($tex,'Invalid TC command parameter: '.$param);
1619 return undef;
1620 }
1621
1622
1623
1624 ###### Macro rules handling
1625
1626
1627 # Takes hash, value, list of keys and adds mappings to hash
1628 sub add_keys_to_hash {
1629 my $hash=shift @_;
1630 my $value=shift @_;
1631 foreach (@_) {
1632 $hash->{$_}=$value;
1633 }
1634 }
1635
1636 # Add source hash to target hash, optionally converting values
1637 sub __add_to_hash {
1638 my $target=shift @_;
1639 my $source=shift @_;
1640 my $convert=shift @_;
1641 if (!defined $convert) {$convert=&__dummy;}
1642 while (my ($key,$val)=each(%$source)) {
1643 $target->{$key}=$convert->($val,@_);
1644 }
1645 }
1646
1647 # Convert hash by applying function to all values
1648 sub convert_hash {
1649 my $hash=shift @_;
1650 my $convert=shift @_;
1651 while (my ($key,$val)=each(%$hash)) {
1652 $hash->{$key}=$convert->($val,@_);
1653 }
1654 }
1655
1656 # Convert key to parser state constant
1657 sub key_to_state {
1658 my ($key,$tex)=@_;
1659 return key_convert(lc($key),$tex,\%key2state,'Unknown state key {key} replaced by IGNORE.',$STATE_IGNORE);
1660 }
1661
1662 # Convert key array to parser state constants
1663 sub keyarray_to_state {
1664 my ($array,$tex)=@_;
1665 return keyarray_convert($array,$tex,\&key_to_state);
1666 }
1667
1668 # Convert key to counter constant
1669 sub key_to_cnt {
1670 my ($key,$tex)=@_;
1671 return key_convert(lc($key),$tex,\%key2cnt,'Unknown counter key {key} ignored.');
1672 }
1673
1674 # Convert key array to counter constants
1675 sub keyarray_to_cnt {
1676 my ($array,$tex)=@_;
1677 return keyarray_convert($array,$tex,\&key_to_cnt);
1678 }
1679
1680 # Convert key to value using map
1681 sub key_convert {
1682 my ($key,$tex,$map,$error,$default)=@_;
1683 my $value=$map->{$key};
1684 if (!defined $value) {
1685 if (!defined $tex) {$tex=$Main;}
1686 $error=~s/\{key\}/$key/g;
1687 error($tex,$error);
1688 return $default;
1689 }
1690 return $value;
1691 }
1692
1693 # Convert state keys to state nos for arrays
1694 sub keyarray_convert {
1695 my ($array,$tex,$conv)=@_;
1696 if (ref($array) eq 'ARRAY') {
1697 my @ar;
1698 foreach my $key (@$array) {
1699 if (defined (my $cnt=$conv->($key,$tex))) {push @ar,$cnt;}
1700 }
1701 $array=\@ar;
1702 }
1703 return $array;
1704 }
1705
1706 # Convert transition state to parsing state, and increment counter
1707 sub transition_to_content_state {
1708 my ($tex,$state)=@_;
1709 my $tr=$transition2state{$state};
1710 if (defined $tr) {
1711 if (my $cnt=$tr->[1]) {inc_count($tex,$tr->[1]);}
1712 return $tr->[0];
1713 }
1714 return $state;
1715 }
1716
1717 # Remove all rules
1718 sub remove_all_rules {
1719 %TeXpackageinc=();
1720 %TeXpreamble=();
1721 %TeXfloatinc=();
1722 %TeXmacro=();
1723 %TeXmacrocount=();
1724 %TeXenvir=();
1725 %TeXfileinclude=();
1726 %IncludedPackages=();
1727 }
1728
1729 # Process package inclusion
1730 sub include_package {
1731 my ($incpackage,$tex)=@_;
1732 if (defined $IncludedPackages{$incpackage}) {return;}
1733 $IncludedPackages{$incpackage}=1;
1734 # Add rules for package, preamble and float inclusion, and add to macro rules
1735 _add_package(\%TeXpackageinc,\%PackageTeXpackageinc,$incpackage,\&__dummy,$tex);
1736 _add_package(\%TeXpreamble,\%PackageTeXpreamble,$incpackage,\&keyarray_to_state,$tex);
1737 _add_package(\%TeXfloatinc,\%PackageTeXfloatinc,$incpackage,\&keyarray_to_state,$tex);
1738 _add_package(\%TeXmacro,\%PackageTeXpackageinc,$incpackage,\&keyarray_to_state,$tex);
1739 _add_package(\%TeXmacro,\%PackageTeXpreamble,$incpackage,\&keyarray_to_state,$tex);
1740 _add_package(\%TeXmacro,\%PackageTeXfloatinc,$incpackage,\&keyarray_to_state,$tex);
1741 # Add regular rules
1742 _add_package(\%TeXmacro,\%PackageTeXmacro,$incpackage,\&keyarray_to_state,$tex);
1743 _add_package(\%TeXmacrocount,\%PackageTeXmacrocount,$incpackage,\&keyarray_to_cnt,$tex);
1744 _add_package(\%TeXenvir,\%PackageTeXenvir,$incpackage,\&key_to_state,$tex);
1745 _add_package(\%TeXfileinclude,\%PackageTeXfileinclude,$incpackage,\&__dummy,$tex);
1746 if (my $subpackages=$PackageSubpackage{$incpackage}) {
1747 foreach my $sub (@{$subpackages}) {
1748 include_package($sub,$tex);
1749 }
1750 }
1751 }
1752
1753 # Add package rules if defined
1754 sub _add_package {
1755 my ($target,$source,$name,$convert,$tex)=@_;
1756 my $sub;
1757 if ($sub=$source->{$name}) {
1758 __add_to_hash($target,$sub,$convert);
1759 }
1760 }
1761
1762 # Dummy conversion function: returns arguments unchanged
1763 sub __dummy {
1764 return shift @_;
1765 }
1766
1767
1768 ###### TeX code handle
1769
1770
1771
1772 # Return object capable of capturing errors for use when
1773 # no TeXcode object is available.
1774 sub getMain {
1775 my %main=();
1776 $main{'errorcount'}=0;
1777 $main{'errorbuffer'}=[];
1778 $main{'warnings'}={};
1779 return \%main;
1780 }
1781
1782
1783 ## Make TeX handle for LaTeX code: the main TeXcount object
1784 # The "TeX object" is a data containser: a hash containing
1785 # - filepath: path of LaTeX file being parsed
1786 # - filename: file name of LaTeX file
1787 # - dirpath: path to directory containing LaTeX file
1788 # - PATH: array of paths to search for included files
1789 # - countsum: count object with total count (incl. subcounts)
1790 # - subcount: count object for subcount (to be added to countsum)
1791 # - subcounts: list of subcounts
1792 # - errorcount: the number of errors reported
1793 # plus following elements used for the processing the LaTeX code
1794 # - line: the LaTeX paragraph being processed
1795 # - texcode: what remains of LaTeX code to process (after line)
1796 # - texlength: length of LaTeX code
1797 # - next: the next token, i.e. the one being processed
1798 # - type: the type of the next token
1799 # - style: the present output style (for verbose output)
1800 # - printstate: present parsing state (for verbose output only)
1801 # - eof: set once the end of the input is reached
1802 # which are passed to methods by passing the TeX object. It is used when parsing
1803 # the LaTeX code, and discarded once the parsing is done. During parsing, counts
1804 # are added to the subcount element; whenever a break point is encountered, the
1805 # subcount is added to the countsum (next_subcount) and a new subcount object
1806 # prepared. Note that this requires that the last subcount object be added to
1807 # the countsum once the end of the document is reached.
1808 sub TeXcode {
1809 my ($bincode,$file,$title)=@_;
1810 my $tex=_TeXcode_blank($file,$title);
1811 _TeXcode_setcode($tex,$bincode);
1812 more_texcode($tex);
1813 return $tex;
1814 }
1815
1816 # Return a blank TeXcode object
1817 sub _TeXcode_blank {
1818 my ($file,$title)=@_;
1819 if (defined $title) {}
1820 elsif (defined $file) {$title='File: '.$file;}
1821 else {$title='Word count';}
1822 my %TeX=();
1823 $TeX{'errorcount'}=0;
1824 $TeX{'warnings'}={};
1825 $TeX{'filepath'}=$file;
1826 if (!defined $file) {}
1827 elsif ($file=~/^<.+>$/) {$TeX{'filename'}=$file;}
1828 elsif ($file=~/^(.*[\\\/])([^\\\/]+)$/) {
1829 $TeX{'dirpath'}=$1; $TeX{'filename'}=$2;
1830 }
1831 else {$TeX{'dirpath'}=''; $TeX{'filename'}=$file;}
1832 $TeX{'PATH'}=[];
1833 $TeX{'line'}='';
1834 $TeX{'next'}=undef;
1835 $TeX{'type'}=undef;
1836 $TeX{'style'}=undef;
1837 $TeX{'printstate'}=undef;
1838 $TeX{'eof'}=0;
1839 my $countsum=new_count($title);
1840 $TeX{'countsum'}=$countsum;
1841 $countsum->{'TeXcode'}=\%TeX;
1842 my $count=new_count('_top_');
1843 $TeX{'subcount'}=$count;
1844 inc_count(\%TeX,$CNT_FILE);
1845 return \%TeX;
1846 }
1847
1848 # Set the texcode element of the TeXcount object
1849 sub _TeXcode_setcode {
1850 my ($tex,$bincode)=@_;
1851 $tex->{'texcode'}=_prepare_texcode($tex,$bincode);
1852 $tex->{'texlength'}=length($tex->{'texcode'});
1853 }
1854
1855 # Decode and return TeX/LaTeX code
1856 sub _prepare_texcode {
1857 my ($tex,$texcode)=@_;
1858 $texcode=_decode_texcode($tex,$texcode);
1859 foreach my $key (keys %substitutions) {
1860 my $value=$substitutions{$key};
1861 $texcode=~s/(\w)\Q$key\E/$1 $value/g;
1862 $texcode=~s/\Q$key\E/$value/g;
1863 }
1864 return $texcode;
1865 }
1866
1867 # Return text decoder
1868 sub _decode_texcode {
1869 my ($tex,$texcode)=@_;
1870 my $decoder;
1871 if (defined $encoding) {
1872 $decoder=find_encoding($encoding);
1873 eval {$texcode=$decoder->decode($texcode);};
1874 if ($@) {
1875 error($tex,'Decoding file/text using the '.$decoder->name.' encoding failed.');
1876 }
1877 } else {
1878 ($texcode,$decoder)=_guess_encoding($texcode);
1879 if (!ref($decoder)) {
1880 error($tex,'Failed to identify encoding or incorrect encoding specified.');
1881 $tex->{'encoding'}='[FAILED]';
1882 return $texcode;
1883 }
1884 }
1885 __set_encoding_name($tex,$decoder->name);
1886 $texcode =~ s/^\x{feff}//; # Remove BOM (relevant for UTF only)
1887 if ($texcode =~/\x{fffd}/ ) {
1888 error($tex,'File/text was not valid '.$decoder->name.' encoded.');
1889 }
1890 return $texcode;
1891 }
1892
1893 # Guess the right encoding to use
1894 sub _guess_encoding {
1895 my ($texcode)=@_;
1896 foreach my $enc (@encodingGuessOrder) {
1897 my $dec=find_encoding($enc);
1898 if (ref($dec)) {
1899 eval {
1900 $texcode=$dec->decode($texcode,Encode::FB_CROAK)
1901 };
1902 if (!$@) {return $texcode,$dec;}
1903 }
1904 }
1905 return $texcode,undef;
1906 }
1907
1908 # Set name of current encoding
1909 sub __set_encoding_name {
1910 my ($tex,$enc)=@_;
1911 my $cur=$tex->{'encoding'};
1912 if (!defined $enc) {$enc='[FAILED]';} # Shouldn't happen here though...
1913 if (!defined $cur) {}
1914 elsif ($enc eq 'ascii') {$enc=$cur;}
1915 elsif ($cur eq 'ascii') {}
1916 elsif ($cur ne $enc) {
1917 error($tex,"Mismatching encodings: $cur versus $enc.");
1918 }
1919 $tex->{'encoding'}=$enc;
1920 }
1921
1922 # Apply substitution rule
1923 sub apply_substitution_rule {
1924 my ($tex,$from,$to)=@_;
1925 $tex->{'line'}=~s/(\w)\Q$from\E\b\s*/$1 $to/g;
1926 $tex->{'line'}=~s/\Q$from\E\b\s*/$to/g;
1927 $tex->{'texcode'}=~s/(\w)\Q$from\E\b\s*/$1 $to/g;
1928 $tex->{'texcode'}=~s/\Q$from\E\b\s*/$to/g;
1929 }
1930
1931 ## Get more TeX code from texcode buffer if possible, return 1 if done
1932 sub more_texcode {
1933 my ($tex)=@_;
1934 if ($tex->{'texcode'} eq '') {return 0;}
1935 if ( $optionFast && $tex->{'texcode'} =~ s/^(.*?(\r{2,}|\n{2,}|(\r\n){2,}))//s ) {
1936 $tex->{'line'}.=$1; # $1 ~ ${^MATCH}
1937 return 1;
1938 }
1939 $tex->{'line'}.=$tex->{'texcode'};
1940 $tex->{'texcode'}='';
1941 return 1;
1942 }
1943
1944 ## Prepend LaTeX code to TeXcode object
1945 sub prepend_code {
1946 my ($tex,$code,$filename)=@_;
1947 my $prefix="\n% --- Start of included file $filename\n";
1948 my $suffix="\n% --- End of included file $filename\n";
1949 $code=_decode_texcode($tex,$code);
1950 $tex->{'length'}+=length($code);
1951 $tex->{'texcode'}=$prefix.$code.$suffix.$tex->{'line'}.$tex->{'texcode'};
1952 $tex->{'line'}='';
1953 more_texcode($tex);
1954 }
1955
1956 # Save and return TeXcode state, and replace with new text
1957 sub texcode_insert_text {
1958 my ($tex,$code,$filename,@path)=@_;
1959 my %texstate=(
1960 'texcode'=>$tex->{'line'}.$tex->{'texcode'},
1961 'eof'=>$tex->{'eof'},
1962 'PATH'=>$tex->{'PATH'});
1963 my $prefix="\n% --- Start of included file $filename\n";
1964 my $suffix="\n% --- End of included file $filename\n";
1965 $code=_decode_texcode($tex,$code);
1966 $tex->{'length'}+=length($code);
1967 $tex->{'texcode'}=$prefix.$code.$suffix;
1968 $tex->{'line'}='';
1969 more_texcode($tex);
1970 return \%texstate;
1971 }
1972
1973 # Restore TeXcode state
1974 sub texcode_restore_state {
1975 my ($tex,$texstate)=@_;
1976 while (my ($key,$value)=each %$texstate) {
1977 $tex->{$key}=$value;
1978 }
1979 }
1980
1981 ## Returns size of TeX code in bytes
1982 sub get_texsize {
1983 my $tex=shift @_;
1984 return $tex->{'texlength'}
1985 }
1986
1987
1988
1989 ###### TeX file reader
1990
1991
1992 # Read LaTeX file into TeX object
1993 sub TeXfile {
1994 my ($filename,$title)=@_;
1995 my ($header,$bincode);
1996 if ($filename eq $_STDIN_) {
1997 $header='File from STDIN';
1998 $bincode=_read_stdin();
1999 } else {
2000 defined ($bincode=read_binary($filename)) || return undef;
2001 $header='File: '.$filename;
2002 }
2003 if ($printlevel>0) {
2004 formatprint($header."\n",'h2');
2005 $blankline=0;
2006 }
2007 my $tex=TeXcode($bincode,$filename,$title);
2008 return $tex;
2009 }
2010
2011 # Read file to string without regard for encoding
2012 sub read_binary {
2013 my $filename=shift @_;
2014 open(FH,$filename) || return undef;
2015 binmode(FH);
2016 my $bincode;
2017 read(FH,$bincode,-s FH);
2018 close(FH);
2019 return $bincode;
2020 }
2021
2022 # Read file from STDIN
2023 sub _read_stdin {
2024 my @text=<STDIN>;
2025 my $latexcode=join('',@text);
2026 return $latexcode;
2027 }
2028
2029
2030 ###### Error handling
2031
2032
2033 # Print note to output
2034 sub note {
2035 my ($tex,$level,$text,$prefix,$style)=@_;
2036 if ($printlevel>=$level) {
2037 $prefix=(defined $prefix)?$prefix:'%NOTE: ';
2038 $style=(defined $style)?$style:'note';
2039 $text=count_in_template($tex->{'subcount'},$text);
2040 flush_next($tex);
2041 line_return(0,$tex);
2042 print_style($prefix.$text,$style);
2043 flush_next($tex);
2044 $blankline=-1;
2045 }
2046 }
2047
2048 # Compare count with expected and note if assertion fails
2049 sub assertion_note {
2050 my ($tex,$checktext,$template)=@_;
2051 my $count=$tex->{'subcount'};
2052 my @check=split(/,/,$checktext);
2053 my @actual;
2054 for (my $i=scalar @check;$i>0;$i--) {$actual[$i-1]=get_count($count,$i);}
2055 for (my $i=scalar @check;$i>0;$i--) {
2056 if ($check[$i-1] ne $actual[$i-1]) {
2057 my $msg=$template.' [expected:'.join('+',@check).'; found: '.join('+',@actual).']';
2058 note($tex,0,$msg,'%ASSERTION FAILED: ','error');
2059 return 1;
2060 }
2061 }
2062 return 0;
2063 }
2064
2065 # Add warning to list of registered warnings (optionally to be reported at the end)
2066 sub warning {
2067 my ($tex,$text)=@_;
2068 $warnings{$text}++;
2069 # TODO: should only add warnings to subcount, not to TeXcode object
2070 $tex->{'warnings'}->{$text}++;
2071 if (my $count=$tex->{'subcount'}) {$count->{'warnings'}->{$text}++};
2072 }
2073
2074 # Register error and print error message
2075 sub error {
2076 my ($tex,$text,$type)=@_;
2077 if (defined $type) {$text=$type.': '.$text;}
2078 $errorcount++;
2079 $tex->{'errorcount'}++;
2080 if (my $count=$tex->{'subcount'}) {$count->{'errorcount'}++};
2081 if (my $err=$tex->{'errorbuffer'}) {push @$err,$text;}
2082 else {print_error($text);}
2083 }
2084
2085 # Print error details
2086 sub error_details {
2087 my ($tex,$text)=@_;
2088 print STDERR $text,"\n";
2089 }
2090
2091 # Make assertion: i.e. report error if not true and return truthfullness
2092 sub assert {
2093 my $assertion=shift @_;
2094 if ($assertion) {return 1;}
2095 error(@_);
2096 return 0;
2097 }
2098
2099 # Print error message
2100 sub print_error {
2101 my $text=shift @_;
2102 line_return(1);
2103 if ($printlevel<0) {
2104 print STDERR 'ERROR: ',$text,"\n";
2105 } elsif ($htmlstyle) {
2106 print STDERR 'ERROR: ',$text,"\n";
2107 print_style($text,'error');
2108 } else {
2109 print_style("!!! $text !!!",'error');
2110 }
2111 line_return(1);
2112 }
2113
2114 # Print errors in buffer and delete errorbuffer
2115 sub flush_errorbuffer {
2116 my $source=shift @_;
2117 my $err=$source->{'errorbuffer'} || return;
2118 foreach (@$err) {print_error($_);}
2119 $source->{'errorbuffer'}=undef;
2120 }
2121
2122
2123 ###### Parsing routines
2124
2125
2126 # Parse LaTeX document
2127 sub parse {
2128 my ($tex)=@_;
2129 if ($htmlstyle && $printlevel>0) {print "<div class='parse'><p>\n";}
2130 parse_all($tex);
2131 if ($htmlstyle && $printlevel>0) {print "</p></div>\n";}
2132 }
2133
2134 # Parse until end
2135 sub parse_all {
2136 my ($tex,$state)=@_;
2137 if (!defined $state) {$state=$STATE_TEXT;}
2138 while (!($tex->{'eof'})) {
2139 _parse_unit($tex,$state);
2140 }
2141 }
2142
2143 # Parse one block/unit with given state until end token
2144 # If end token is set to $_PARAM_, unit is assumed to be a parameter
2145 # and words parsed as individual letters (simple_token is set)
2146 sub _parse_unit {
2147 my ($tex,$state,$end)=@_;
2148 my $simple_token=0;
2149 ( assert(defined $state,$tex,'Undefined parser state!','BUG')
2150 && assert(!ref($state),$tex,'Invalid parser state of type '.ref($state).'!','BUG')
2151 ) || exit;
2152 $state=transition_to_content_state($tex,$state);
2153 _set_printstate($tex,$state,$end);
2154 if (defined $end && $end eq $_PARAM_) {
2155 $end=undef;
2156 $simple_token=1;
2157 }
2158 my $next;
2159 my @specarg;
2160 while (defined ($next=next_token($tex,$simple_token))) {
2161 # Parse next token until token matches $end
2162 set_style($tex,'ignore');
2163 if ($state==$STATE_MATH) {set_style($tex,'math');}
2164 if ((defined $end) && ($end eq $next)) {return @specarg;}
2165 # Determine how token should be interpreted
2166 if ($state==$STATE_PREAMBLE && $next eq '\begin' && $tex->{'line'}=~/^\{\s*document\s*\}/) {
2167 # \begin{document}
2168 $state=$STATE_TEXT;
2169 }
2170 # Pick the first matching interpretation:
2171 if ($state==$STATE_EXCLUDE_ALL) {
2172 # ignore everything
2173 } elsif ($tex->{'type'}==$TOKEN_SPACE) {
2174 # space or other code that should be passed through without styling
2175 flush_next($tex,' ');
2176 } elsif ($next eq '{') {
2177 # {...} group
2178 set_style($tex,'ignore');
2179 push @specarg,_parse_unit($tex,$state,'}');
2180 set_style($tex,'ignore');
2181 } elsif ($next eq '}') {
2182 error($tex,'Encountered } without corresponding {.');
2183 } elsif ($tex->{'type'}==$TOKEN_TC) {
2184 # parse TC instructions
2185 _parse_tc($tex,$next);
2186 } elsif ($state==$STATE_SPECIAL_ARGUMENT) {
2187 set_style($tex,'specarg');
2188 push @specarg,$next;
2189 } elsif ($tex->{'type'}==$TOKEN_WORD) {
2190 # word
2191 if (my $cnt=state_text_cnt($state)) {
2192 _process_word($tex,$next,$state);
2193 inc_count($tex,$cnt);
2194 set_style($tex,state_to_style($state));
2195 }
2196 } elsif ($state==$STATE_EXCLUDE_STRONGER) {
2197 # ignore remaining tokens
2198 set_style($tex,'ignore');
2199 } elsif ($next eq '\documentclass') {
2200 # defines document class and starts preamble
2201 set_style($tex,'document');
2202 _parse_documentclass_params($tex);
2203 while (!($tex->{'eof'})) {
2204 push @specarg,_parse_unit($tex,$STATE_PREAMBLE);
2205 }
2206 } elsif ($tex->{'type'}==$TOKEN_MACRO) {
2207 # macro call
2208 _parse_macro($tex,$next,$state);
2209 } elsif ($next eq '$') {
2210 # math inline
2211 _parse_math($tex,$state,$CNT_COUNT_INLINEMATH,'$');
2212 } elsif ($next eq '$$') {
2213 # math display (unless already in inlined math)
2214 if (!(defined $end && $end eq '$')) {
2215 _parse_math($tex,$state,$CNT_COUNT_DISPLAYMATH,'$$');
2216 }
2217 } elsif ($simple_token) {
2218 #DELETE: simple tokens should be handled properly
2219 #print STDERR '<',$next,'>',"\n";
2220 # handle as parameter that should not be counted
2221 set_style($tex,'ignore');
2222 }
2223 if (!defined $end) {return @specarg;}
2224 }
2225 defined $end && error($tex,'Reached end of file while waiting for '.$end.'.');
2226 return @specarg;
2227 }
2228
2229 # Print state
2230 sub _set_printstate {
2231 my ($tex,$state,$end)=@_;
2232 $tex->{'printstate'}=':'.state_to_text($state).(defined $end?'>'.$end:'').':';
2233 flush_next($tex);
2234 }
2235
2236 # Process word with a given state (>0, i.e. counted)
2237 sub _process_word {
2238 my ($tex,$word,$state)=@_;
2239 $WordFreq{$word}++;
2240 }
2241
2242 # Parse unit when next token is a macro
2243 sub _parse_macro {
2244 my ($tex,$next,$state)=@_;
2245 my $substat;
2246 my @macro=($next);
2247 if (my $label=$BreakPoints{$next}) {
2248 if ($tex->{'line'}=~ /^[*]?(\s*\[.*?\])*\s*\{((.|\{.*\})*)\}/ ) {
2249 $label=$label.': '.$2;
2250 }
2251 next_subcount($tex,$label);
2252 }
2253 if ($state==$STATE_MATH) {set_style($tex,'mathcmd');}
2254 elsif ($state==$STATE_SPECIAL_ARGUMENT) {set_style($tex,'specarg');}
2255 else {set_style($tex,state_is_text($state)?'cmd':'exclcmd');}
2256 if ($next eq '\begin' && state_inc_envir($state)) {
2257 _parse_envir($tex,$state);
2258 push @macro,'<envir>';
2259 } elsif ($next eq '\end' && state_inc_envir($state)) {
2260 error($tex,'Encountered \end without corresponding \begin');
2261 push @macro,$STRING_ERROR;
2262 } elsif ($next eq '\verb') {
2263 _parse_verb_region($tex,$state);
2264 } elsif (state_is_parsed($state) && defined (my $substat=$TeXpackageinc{$next})) {
2265 # Parse macro parameters, use _parse_include_argument to process package list
2266 set_style($tex,'document');
2267 push @macro,__gobble_macro_parms($tex,$substat,$__STATE_NULL,\&_parse_include_argument);
2268 push @macro,'<package>';
2269 } elsif (state_is_parsed($state) && defined (my $def=$TeXfileinclude{$next})) {
2270 # include file (merge in or queue up for parsing)
2271 set_style($tex,'cmd');
2272 if (defined ($substat=$TeXmacro{'@pre'.$next})) {__gobble_macro_parms($tex,$substat,$state);}
2273 __count_macrocount($tex,$next,$state);
2274 _parse_include_file($tex,$state,$def);
2275 push @macro,'<filespec>';
2276 if (defined ($substat=$TeXmacro{'@post'.$next})) {__gobble_macro_parms($tex,$substat,$state);}
2277 } elsif (($state==$STATE_FLOAT) && ($substat=$TeXfloatinc{$next})) {
2278 # text included from float
2279 set_style($tex,'cmd');
2280 push @macro,__gobble_macro_parms($tex,$substat,$__STATE_NULL);
2281 } elsif ($state==$STATE_PREAMBLE && defined ($substat=$TeXpreamble{$next})) {
2282 # parse preamble include macros
2283 set_style($tex,'cmd');
2284 __count_macrocount($tex,$next,$STATE_TEXT);
2285 push @macro,__gobble_macro_parms($tex,$substat,$__STATE_NULL);
2286 } elsif (state_is_exclude($state)) {
2287 # ignore
2288 push @macro,__gobble_options($tex),'/*ignored*/';
2289 } elsif ($next eq '\(') {
2290 # math inline
2291 _parse_math($tex,$state,$CNT_COUNT_INLINEMATH,'\)');
2292 } elsif ($next eq '\[') {
2293 # math display
2294 _parse_math($tex,$state,$CNT_COUNT_DISPLAYMATH,'\]');
2295 } elsif ($next=~/^\\(def|edef|gdef|xdef)$/) {
2296 # ignore \def...
2297 $tex->{'line'} =~ s/^([^\{]*)\{/\{/;
2298 flush_next($tex);
2299 print_style($1,'ignore');
2300 _parse_unit($tex,$STATE_EXCLUDE_STRONG);
2301 push @macro,'<macro>',$STRING_PARAMETER;
2302 } elsif (defined ($substat=$TeXmacro{$next})) {
2303 # macro: exclude options
2304 __count_macrocount($tex,$next,$state);
2305 push @macro,__gobble_macro_parms($tex,$substat,$state);
2306 } elsif (defined __count_macrocount($tex,$next,$state)) {
2307 # count macro as word (or a given number of words)
2308 } elsif ($next =~ /^\\[^\w\_]$/) {
2309 # handle \<symbol> as single symbol macro
2310 push @macro,__gobble_options($tex),'/*symbol*/';
2311 } else {
2312 push @macro,__gobble_options($tex),'/*defaultrule*/';
2313 }
2314 $MacroUsage{join('',@macro)}++;
2315 }
2316
2317 # Parse TC instruction
2318 sub _parse_tc {
2319 my ($tex,$next)=@_;
2320 set_style($tex,'tc');
2321 flush_next($tex);
2322 assert($next=~s/^\%+TC:\s*(\w+)\s*//i
2323 ,$tex,'TC command should have format %TC:instruction [[parameters]]')
2324 || return;
2325 my $instr=$1;
2326 $instr=~tr/[A-Z]/[a-z]/;
2327 if ($instr eq 'break') {next_subcount($tex,$next);
2328 } elsif ($instr=~/^(incbib|includebibliography)$/) {
2329 $includeBibliography=1;
2330 apply_include_bibliography();
2331 } elsif ($instr eq 'ignore') {__gobble_tc_ignore($tex);
2332 } elsif ($instr eq 'endignore') {error($tex,'%TC:endignore without corresponding %TC:ignore.');
2333 } elsif ($instr eq 'newtemplate') {$outputtemplate='';
2334 } elsif ($instr eq 'template') {$outputtemplate.=$next;
2335 } elsif ($instr eq 'insert') {
2336 $tex->{'line'}="\n".$next.$tex->{'line'};
2337 } elsif ($instr eq 'subst') {
2338 if ($next=~/^(\S+)\s*(\S.*)?$/) {
2339 my $from=$1;
2340 my $to=$2;
2341 $substitutions{$from}=$to;
2342 apply_substitution_rule($tex,$from,$to);
2343 } else {
2344 error($tex,'Invalid %TC:subst format.');
2345 }
2346 } elsif ($instr eq 'newcounter') {
2347 assert($next=~s/^(\w+)(=(\w+))?\s*//,$tex,'Expected format: %TC:newcounter {key}[={like-key}] {description}')
2348 || return;
2349 my $key=$1;
2350 my $like=$3;
2351 if ($next eq '') {$next=$key;}
2352 add_new_counter($key,$next,$like);
2353 } elsif ($instr eq 'log') {
2354 assert($next=~s/^(.*)$//,$tex,'Expected format: %TC:log {text or template}') || return;
2355 note($tex,1,$1);
2356 } elsif ($instr eq 'assert') {
2357 assert($next=~s/^(\d+(,\d+)*)(\s+(.*))?$//,$tex,'Expected format: %TC:assert count+count+... {text or template}')
2358 || return;
2359 my $template=$4 || 'Words counted: {w} in text, {hw} in headers, {ow} other.';
2360 assertion_note($tex,$1,$template);
2361 } elsif ($next=~/^([\\]*\S+)\s+([^\s]+)(\s+(-?\w+))?/) {
2362 # %TC:instr macro param option
2363 my $macro=$1;
2364 my $param=$2;
2365 my $option=$4;
2366 tc_macro_param_option($tex,$instr,$macro,$param,$option);
2367 } else {
2368 error($tex,'Invalid TC command: '.$instr);
2369 }
2370 }
2371
2372 # Parse math formulae
2373 sub _parse_math {
2374 my ($tex,$state,$cnt,$end)=@_;
2375 my $localstyle;
2376 if (state_is_text($state)) {
2377 $localstyle='mathgroup';
2378 inc_count($tex,$cnt);
2379 } else {
2380 $localstyle='exclmath';
2381 }
2382 set_style($tex,$localstyle);
2383 _parse_unit($tex,$STATE_MATH,$end);
2384 set_style($tex,$localstyle);
2385 }
2386
2387 # Parse \verb region
2388 sub _parse_verb_region {
2389 my ($tex,$state)=@_;
2390 #flush_next($tex);
2391 __gobble_macro_modifier($tex);
2392 set_style($tex,'ignore');
2393 assert($tex->{'line'} =~ s/^([^\s])//,$tex,'Invalid \verb: delimiter required.')
2394 || return;
2395 my $dlm=$1;
2396 print_style($dlm,'cmd');
2397 assert($tex->{'line'}=~s/^([^\Q$dlm\E]*)(\Q$dlm\E)//
2398 ,$tex,'Invalid \verb: could not find ending delimiter ('.$dlm.').')
2399 || return;
2400 print_style($1,'ignore');
2401 print_style($2,'cmd');
2402 }
2403
2404 # Parse environment
2405 sub _parse_envir {
2406 my ($tex,$state)=@_;
2407 my $localstyle=state_is_text($state) ? 'envir' : 'exclenv';
2408 flush_next_gobble_space($tex,$localstyle,$state);
2409 my ($envirname,$next);
2410 if ($tex->{'line'} =~ s/^\{([^\{\}\s]+)\}[ \t\r\f]*//) {
2411 # gobble environment name
2412 $envirname=$1;
2413 my @macro=('<envir:'.$envirname.'>');
2414 print_style('{'.$1.'}',$localstyle);
2415 $next=$PREFIX_ENVIR.$envirname;
2416 __count_macrocount($tex,$next,$state);
2417 if (defined (my $def=$TeXmacro{$next})) {
2418 push @macro,__gobble_macro_parms($tex,$def,$__STATE_NULL);
2419 } else {
2420 push @macro,__gobble_options($tex);
2421 }
2422 $MacroUsage{join('',@macro)}++;
2423 } else {
2424 $envirname='???'; $next='???';
2425 error($tex,'Encountered \begin without environment name provided.');
2426 }
2427 # find new parsing state (or leave unchanged)
2428 my $substat=$TeXenvir{$1};
2429 if (!defined $substat) {
2430 $substat=$state;
2431 if ($strictness>=1) {
2432 warning($tex,'Using default rule for environment '.$envirname);
2433 }
2434 } else {
2435 $substat=__new_state($substat,$state);
2436 }
2437 if (state_inc_envir($substat)) {
2438 # Parse until \end arrives, and check that it matches
2439 _parse_unit($tex,$substat,'\end');
2440 flush_next_gobble_space($tex,$localstyle,$state);
2441 if ($tex->{'line'} =~ s/^\{([^\{\}\s]+)\}[ \t\r\f]*//) {
2442 # gobble environment name
2443 print_style('{'.$1.'}',$localstyle);
2444 assert($envirname eq $1,$tex,"Environment \\begin{$envirname} ended with \\end{$1}.");
2445 } else {
2446 error($tex,"Environment ended while waiting for \end{$envirname}.");
2447 }
2448 } else {
2449 # Keep parsing until appropriate \end arrives ignoring all else
2450 while (!$tex->{'eof'}) {
2451 _parse_unit($tex,$substat,'\end');
2452 if ($tex->{'line'} =~ s/^(\s*)(\{\Q$envirname\E\})[ \t\r\f]*//) {
2453 # gobble \end parameter and end environment
2454 flush_next($tex,$localstyle,$state);
2455 print_style($1,$localstyle);
2456 print_style($2,$localstyle);
2457 return;
2458 }
2459 }
2460 }
2461 }
2462
2463 # Parse and process file inclusion
2464 sub _parse_include_file {
2465 my ($tex,$state,$includetype)=@_;
2466 my $include=state_is_parsed($state);
2467 my $style=$include?'fileinc':'ignore';
2468 my $file;
2469 my %params;
2470 flush_next($tex);
2471 $params{'<type>'}=$includetype;
2472 $params{'SUFFICES'}=[''];
2473 if ($includetype eq '<bbl>') {
2474 _parse_include_bbl($tex,$state,\%params);
2475 return;
2476 }
2477 elsif ($includetype eq 'input') {
2478 $tex->{'line'} =~ s/^(\s*\{([^\{\}\s]+)\})//
2479 || $tex->{'line'} =~ s/^(\s*([^\{\}\%\\\s]+))//
2480 || $tex->{'line'} =~ s/^(\s*\{(.+?)\})//
2481 || BLOCK {
2482 error($tex,'Failed to identify file name.');
2483 return;
2484 };
2485 print_style($1,$style);
2486 $file=$2;
2487 if (!($file=~/\.tex$/i)) {$params{'SUFFICES'}=['.tex',''];}
2488 }
2489 else {
2490 foreach my $param (split(/\s+|,/,$includetype)) {
2491 if ($param=~/^<.*>$/) {next;}
2492 $tex->{'line'} =~ s/(\s*\{)([^\{\}\%]*)(\})//|| BLOCK {
2493 error($tex,"Failed to identify file parameter {$param}.");
2494 return;
2495 };
2496 print_style($1,'ignore');
2497 print_style($2,$style);
2498 print_style($3,'ignore');
2499 if ($param eq 'file') {
2500 $file=$2;
2501 if (!($file=~/\.tex$/i)) {$params{'SUFFICES'}=['.tex',''];}
2502 } elsif ($param eq 'texfile') {
2503 $file=$2.'.tex';
2504 } else {$params{$param}=$2;}
2505 }
2506 }
2507 if (!defined $file) {
2508 error($tex,'Undefined file name.');
2509 }
2510 elsif ($includeTeX && $include) {
2511 include_file($tex,$state,$file,\%params);
2512 }
2513 }
2514
2515 # Parse and process bibliography file
2516 sub _parse_include_bbl {
2517 my ($tex,$state,$params)=@_;
2518 if ($includeBibliography && state_is_text($state)) {
2519 my $filename=$tex->{'filename'};
2520 $filename=~s/(\.tex)?$/\.bbl/i;
2521 include_file($tex,$state,$filename,$params);
2522 }
2523 }
2524
2525 # Parse and process package inclusion
2526 sub _parse_include_package {
2527 my ($tex)=@_;
2528 set_style($tex,'document');
2529 if ( $tex->{'line'}=~s/^\{(([\w\-]+)(\s*,\s*[\w\-]+)*)\}// ) {
2530 print_style("{$1}",'document');
2531 foreach (split(/\s*,\s*/,$1)) {
2532 $MacroUsage{"<package:$_>"}++;
2533 include_package($_,$tex);
2534 }
2535 } else {
2536 _parse_unit($tex,$STATE_IGNORE);
2537 error($tex,'Could not recognise package list, ignoring it instead.');
2538 }
2539 }
2540
2541 # Extract package names from token list and include packages
2542 sub _parse_include_argument {
2543 my $tex=shift @_;
2544 my $args=join('',@_);
2545 set_style($tex,'document');
2546 foreach (split(/\s*,\s*/,$args)) {
2547 $MacroUsage{"<package:$_>"}++;
2548 include_package($_,$tex);
2549 }
2550 }
2551
2552 # Parse \documentclass parameters and include rules
2553 sub _parse_documentclass_params {
2554 my ($tex)=@_;
2555 my $options=__gobble_option($tex);
2556 if ( $tex->{'line'}=~s/^(\{\s*([^\{\}\s]+)\s*\})// ) {
2557 print_style("$1",'document');
2558 $MacroUsage{"<documentclass:$2>"}++;
2559 include_package("class%$2",$tex);
2560 } else {
2561 _parse_unit($tex,$STATE_IGNORE);
2562 error($tex,'Could not identify document class.');
2563 }
2564 }
2565
2566 # Count macrocount using given state
2567 sub __count_macrocount {
2568 my ($tex,$next,$state)=@_;
2569 my $def=$TeXmacrocount{$next};
2570 my $cnt;
2571 if (!defined $def) {return undef;}
2572 elsif (ref($def) eq 'ARRAY') {
2573 # TODO: Is this an appropriate style to use?
2574 set_style($tex,state_to_style($state));
2575 flush_next($tex);
2576 foreach $cnt (@{$def}) {
2577 if ($cnt==$CNT_WORDS_TEXT) {$cnt=state_text_cnt($state);}
2578 inc_count($tex,$cnt);
2579 }
2580 }
2581 elsif ($cnt=state_text_cnt($state)) {
2582 set_style($tex,state_to_style($state));
2583 flush_next($tex);
2584 inc_count($tex,$cnt,$def);
2585 }
2586 return $def;
2587 }
2588
2589 # Gobble next option, return option or undef if none
2590 sub __gobble_option {
2591 my $tex=shift @_;
2592 flush_next_gobble_space($tex);
2593 if ($tex->{'line'}=~s/^($MacroOptionPattern)//) {
2594 print_style($1,'option');
2595 return $1;
2596 }
2597 return undef;
2598 }
2599
2600 # Gobble all options, return the number of gobble options
2601 sub __gobble_options {
2602 my $n=0;
2603 while (__gobble_option(@_)) {$n++}
2604 return ($STRING_GOBBLED_OPTION)x$n;
2605 }
2606
2607 # Gobble macro modifyer (e.g. following *)
2608 sub __gobble_macro_modifier {
2609 my $tex=shift @_;
2610 flush_next($tex);
2611 if ($tex->{'line'} =~ s/^(\*)//) {
2612 print_style($1,'option');
2613 return $1;
2614 }
2615 return;
2616 }
2617
2618 # Gobble macro parameters as specified in parm plus options
2619 sub __gobble_macro_parms {
2620 my ($tex,$parm,$oldstat,$specarghandler)=@_;
2621 my $n;
2622 my @ret;
2623 if (ref($parm) eq 'ARRAY') {
2624 $n=scalar @{$parm};
2625 } else {
2626 $n=$parm;
2627 $parm=[($STATE_IGNORE)x$n];
2628 }
2629 # TODO: Optionally gobble macro modifier?
2630 if ($n>0) {push @ret,__gobble_macro_modifier($tex);}
2631 my $auto_gobble_options=1;
2632 for (my $j=0;$j<$n;$j++) {
2633 my $p=$parm->[$j];
2634 if ($p==$_STATE_OPTION) {
2635 # Parse macro option
2636 $p=$parm->[++$j];
2637 if ($tex->{'line'}=~s/^(\s*\[)//) {
2638 flush_next_gobble_space($tex);
2639 print_style($1,'optparm');
2640 push @ret,$STRING_OPTIONAL_PARAM;
2641 _parse_unit($tex,__new_state($p,$oldstat),']');
2642 set_style($tex,'optparm');
2643 }
2644 } elsif ($p==$_STATE_NOOPTION) {
2645 $auto_gobble_options=0;
2646 } elsif ($p==$_STATE_AUTOOPTION) {
2647 $auto_gobble_options=1;
2648 } else {
2649 # Parse macro parameter
2650 if ($auto_gobble_options) {push @ret,__gobble_options($tex);}
2651 push @ret,$STRING_PARAMETER;
2652 my @specarg=_parse_unit($tex,__new_state($p,$oldstat),$_PARAM_);
2653 if ($p==$STATE_SPECIAL_ARGUMENT && defined $specarghandler) {
2654 &$specarghandler($tex,@specarg);
2655 }
2656 }
2657 }
2658 #TODO: Drop default gobbling of option at end?
2659 if ($auto_gobble_options) {push @ret,__gobble_options($tex);}
2660 return @ret;
2661 }
2662
2663 # Parse through ignored LaTeX code
2664 sub __gobble_tc_ignore {
2665 my ($tex)=@_;
2666 set_style($tex,'ignore');
2667 _parse_unit($tex,$STATE_EXCLUDE_ALL,'%TC:endignore');
2668 set_style($tex,'tc');
2669 flush_next($tex);
2670 }
2671
2672 # Return new parsing state given old and substate
2673 sub __new_state {
2674 my ($substat,$oldstat)=@_;
2675 if (!defined $oldstat) {return $substat;}
2676 foreach my $st (@STATE_FIRST_PRIORITY,@STATE_MID_PRIORITY,@STATE_LAST_PRIORITY) {
2677 if ($oldstat==$st || $substat==$st) {return $st;}
2678 }
2679 error($Main,'Could not determine new state in __new_state!','BUG');
2680 return $oldstat;
2681 }
2682
2683
2684
2685 ###### Tokenisation routines
2686
2687
2688 # Get next token skipping comments and flushing output buffer
2689 sub next_token {
2690 my ($tex,$simple_token)=@_;
2691 if (!defined $simple_token) {$simple_token=0;}
2692 my ($next,$type);
2693 my $style=$tex->{'style'};
2694 if (defined $tex->{'next'}) {print_style($tex->{'next'},$tex->{'style'});}
2695 $tex->{'style'}=undef;
2696 while (defined ($next=_get_next_token($tex,$simple_token))) {
2697 $type=$tex->{'type'};
2698 if ($type==$TOKEN_COMMENT) {
2699 print_style($next,'comment');
2700 } elsif ($type==$TOKEN_LINEBREAK) {
2701 if ($printlevel>0) {line_return(-1,$tex);}
2702 } else {
2703 return $next;
2704 }
2705 }
2706 return $next;
2707 }
2708
2709 # Read, interpret and return next token
2710 # If simple_token is set, words cannot form tokens
2711 sub _get_next_token {
2712 my ($tex,$simple_token)=@_;
2713 my $next;
2714 my $ch;
2715 while (!$tex->{'eof'}) {
2716 $ch=substr($tex->{'line'},0,1);
2717 if ($ch eq '') {
2718 if (!more_texcode($tex)) {$tex->{'eof'}=1;}
2719 next;
2720 } elsif ($ch=~/^[ \t\f]/) {
2721 $tex->{'line'}=~s/^([ \t\f]+)//;
2722 return __set_token($tex,$1,$TOKEN_SPACE);
2723 } elsif ($ch eq "\n" || $ch eq "\r") {
2724 $tex->{'line'}=~s/^(\r\n?|\n)//;
2725 return __set_token($tex,$1,$TOKEN_LINEBREAK);
2726 } elsif (!$simple_token && $tex->{'line'}=~s/^($WordPattern)//o) {
2727 return __set_token($tex,$1,$TOKEN_WORD);
2728 } elsif ($simple_token && $tex->{'line'}=~s/^(\w)//) {
2729 # When parsing simple tokens (not words), only include single characters
2730 # TODO: the handling of simple tokens should be improved
2731 my $match=$1;
2732 if ($match=~/^$WordPattern$/) {return __set_token($tex,$match,$TOKEN_WORD);}
2733 else {return __set_token($tex,$match,$TOKEN_SYMBOL);}
2734 } elsif ($ch eq '\\') {
2735 if ($tex->{'line'}=~s/^(\\[\{\}%])//) {return __set_token($tex,$1,$TOKEN_SYMBOL);}
2736 if ($tex->{'line'}=~s/^(\\([a-zA-Z@]+|[^a-zA-Z@[:^print:]]))//) {return __set_token($tex,$1,$TOKEN_MACRO);}
2737 return __get_chtoken($tex,$ch,$TOKEN_END);
2738 } elsif ($ch eq '$') {
2739 $tex->{'line'}=~s/^(\$\$?)//;
2740 return __set_token($tex,$1,$TOKEN_MATH);
2741 } elsif ($ch eq '{' || $ch eq '}') {
2742 return __get_chtoken($tex,$ch,$TOKEN_BRACE);
2743 } elsif ($ch eq '[' || $ch eq ']') {
2744 return __get_chtoken($tex,$ch,$TOKEN_BRACKET);
2745 } elsif ($ch=~/^['"`:.,()[]!+-*=\/^_@<>~#&]$/) {
2746 return __get_chtoken($tex,$ch,$TOKEN_SYMBOL);
2747 } elsif ($ch eq '%') {
2748 if ($tex->{'line'}=~s/^(\%+TC:\s*endignore\b[^\r\n]*)//i) {
2749 __set_token($tex,$1,$TOKEN_TC);
2750 return "%TC:endignore";
2751 }
2752 if ($tex->{'line'}=~s/^(\%+[tT][cC]:[^\r\n]*)//) {return __set_token($tex,$1,$TOKEN_TC);}
2753 if ($tex->{'line'}=~s/^(\%+[^\r\n]*)//) {return __set_token($tex,$1,$TOKEN_COMMENT);}
2754 return __get_chtoken($tex,$ch,$TOKEN_COMMENT);
2755 } else {
2756 return __get_chtoken($tex,$ch,$TOKEN_END);
2757 }
2758 }
2759 return undef;
2760 }
2761
2762 # Set next token and its type
2763 sub __set_token {
2764 my ($tex,$next,$type)=@_;
2765 $tex->{'next'}=$next;
2766 $tex->{'type'}=$type;
2767 return $next;
2768 }
2769
2770 # Set character token and remove from line
2771 sub __get_chtoken {
2772 my ($tex,$ch,$type)=@_;
2773 $tex->{'line'}=substr($tex->{'line'},1);
2774 $tex->{'next'}=$ch;
2775 $tex->{'type'}=$type;
2776 return $ch;
2777 }
2778
2779
2780
2781 ###### Count handling routines
2782
2783
2784
2785 ## Make new count object
2786 # The "count object" is a hash containing:
2787 # - title: the title of the count (name of file, section, ...)
2788 # - counts: a list of numbers (the counts: files, text words, ...)
2789 # - subcounts: list of count objects (used by the TeX object)
2790 # - warnings: list of warnings produced
2791 # The elements are specified by the $CONT_* constants.
2792 sub new_count {
2793 my ($title)=@_;
2794 my @cnt=(0) x $SIZE_CNT;
2795 my %count=('counts'=>\@cnt,'title'=>$title,'subcounts'=>[],'errorcount'=>0,'warnings'=>{});
2796 return \%count;
2797 }
2798
2799 # Ensure the count array is of the right size
2800 sub update_count_size {
2801 my $count=shift @_;
2802 my $counts=$count->{'counts'};
2803 while (scalar @{$counts}<$SIZE_CNT) {push @$counts,0;}
2804 }
2805
2806 # Increment TeX count for a given count type
2807 sub inc_count {
2808 my ($tex,$cnt,$value)=@_;
2809 my $count=$tex->{'subcount'};
2810 if (!defined $value) {$value=1;}
2811 ${$count->{'counts'}}[$cnt]+=$value;
2812 }
2813
2814 # Get count value for a given count type
2815 sub get_count {
2816 my ($count,$cnt)=@_;
2817 my $counts=$count->{'counts'};
2818 if ($cnt<scalar @{$counts}) {return ${$counts}[$cnt];}
2819 else {return 0;}
2820 }
2821
2822 # Compute sum count for a count object
2823 sub get_sum_count {
2824 my $count=shift @_;
2825 my $sum=0;
2826 for (my $i=scalar(@sumweights);$i-->1;) {
2827 if ($sumweights[$i]) {
2828 $sum+=get_count($count,$i)*$sumweights[$i];
2829 }
2830 }
2831 return $sum;
2832 }
2833
2834 # Returns the number of subcounts
2835 sub number_of_subcounts {
2836 my $count=shift @_;
2837 if (my $subcounts=$count->{'subcounts'}) {
2838 return scalar(@{$subcounts});
2839 } else {
2840 return 0;
2841 }
2842 }
2843
2844 # Returns the number of warnings (not distinct)
2845 sub number_of_warnings {
2846 my $count=shift @_;
2847 my $n=0;
2848 foreach my $m (values %{$count->{'warnings'}}) {$n+=$m;}
2849 return $n;
2850 }
2851
2852 # Returns the number of distinct warnings
2853 sub number_of_distinct_warnings {
2854 my $count=shift @_;
2855 return scalar keys %{$count->{'warnings'}};
2856 }
2857
2858 # Is a null count? (counts 1-7 zero, title starts with _)
2859 sub _count_is_null {
2860 my $count=shift @_;
2861 if (!$count->{'title'}=~/^_/) {return 0;}
2862 for (my $i=1;$i<$SIZE_CNT;$i++) {
2863 if (get_count($count,$i)>0) {return 0;}
2864 }
2865 if (scalar keys %{$count->{'warnings'}}) {return 0;}
2866 if ($count->{'errorcount'}) {return 0;}
2867 return 1;
2868 }
2869
2870 # Add one count to another
2871 sub _add_to_count {
2872 my ($a,$b)=@_;
2873 update_count_size($a);
2874 update_count_size($b);
2875 for (my $i=0;$i<$SIZE_CNT;$i++) {
2876 ${$a->{'counts'}}[$i]+=${$b->{'counts'}}[$i];
2877 }
2878 while (my ($text,$n)=each %{$a->{'warnings'}}) {
2879 $a->{'warnings'}->{$text}+=$n;
2880 }
2881 $a->{'errorcount'}+=$b->{'errorcount'};
2882 }
2883
2884 # Add subcount to sum count and prepare new subcount
2885 sub next_subcount {
2886 my ($tex,$title)=@_;
2887 add_to_total($tex->{'countsum'},$tex->{'subcount'});
2888 $tex->{'subcount'}=new_count($title);
2889 return $tex->{'countsum'};
2890 }
2891
2892 # Add count to total as subcount
2893 sub add_to_total {
2894 my ($total,$count)=@_;
2895 _add_to_count($total,$count);
2896 if (_count_is_null($count)) {return;}
2897 push @{$total->{'subcounts'}},$count;
2898 $count->{'parentcount'}=$total;
2899 }
2900
2901
2902 ###### Result output routines
2903
2904
2905 # Close the output (STDOUT), e.g. adding HTML tail
2906 sub Close_Output {
2907 if ($htmlstyle==$HTML_FULL) {
2908 html_tail();
2909 }
2910 close STDOUT;
2911 }
2912
2913 # Report if there were any errors occurring during parsing
2914 sub Report_Errors {
2915 if (defined $outputtemplate) {return;}
2916 if ( !$briefsum && !$totalflag && $printlevel>=0 ) {
2917 foreach (keys %warnings) {formatprint($_,'p','nb');print "\n";}
2918 }
2919 if ($errorcount==0) {return;}
2920 if ($briefsum && $totalflag) {print ' ';}
2921 if ($htmlstyle) {
2922 print "<div class='error'><p>\n";
2923 print "There were $errorcount error(s) reported!\n";
2924 print "</p></div>\n";
2925 } elsif ($briefsum && $totalflag) {
2926 print "(errors:$errorcount)";
2927 } else {
2928 print "(errors:$errorcount)\n";
2929 }
2930 }
2931
2932 # Print word frequencies (as text only)
2933 sub print_word_freq {
2934 my ($word,$wd,$freq,%Freq,%Word,%Class);
2935 my %regs;
2936 foreach my $cg (@AlphabetScripts,@LogogramScripts) {
2937 $regs{$cg}=qr/\p{$cg}/;
2938 }
2939 my $sum=0;
2940 for $word (keys %WordFreq) {
2941 $wd=lc $word;
2942 $Freq{$wd}+=$WordFreq{$word};
2943 $sum+=$WordFreq{$word};
2944 $Word{$wd}=__lc_merge($word,$Word{$wd});
2945 }
2946 if ($htmlstyle) {print "<table class='stat'>\n<thead>\n";}
2947 __print_word_freq('Word','Freq','th');
2948 if ($htmlstyle) {print "</thead>\n";}
2949 if ($optionWordClassFreq>0) {
2950 for $word (keys %Freq) {$Class{__word_class($word,\%regs)}+=$Freq{$word};}
2951 __print_sorted_freqs('langstat',\%Class);
2952 }
2953 if ($htmlstyle) {print "<tbody class='sumstat'>\n";}
2954 __print_word_freq('All words',$sum,'td','sum');
2955 if ($htmlstyle) {print "</tbody>\n";}
2956 if ($optionWordFreq>0) {__print_sorted_freqs('wordstat',\%Freq,\%Word,$optionWordFreq);}
2957 if ($htmlstyle) {print "</table>\n";}
2958 }
2959
2960 # Merge to words which have the same lower case
2961 sub __lc_merge {
2962 my ($word,$w)=@_;
2963 if (defined $w) {
2964 for (my $i=length($word);$i-->0;) {
2965 if (substr($word,$i,1) ne substr($w,$i,1)) {
2966 substr($word,$i,1)=lc substr($word,$i,1);
2967 }
2968 }
2969 }
2970 return $word;
2971 }
2972
2973 # Return the word class based on script groups it contains
2974 sub __word_class {
2975 my ($wd,$regs)=@_;
2976 my @classes;
2977 $wd=~s/\\\w+(\{\})?/\\{}/g;
2978 foreach my $name (keys %{$regs}) {
2979 if ($wd=~$regs->{$name}) {push @classes,$name;}
2980 }
2981 my $cl=join('+',@classes);
2982 if ($cl) {}
2983 elsif ($wd=~/\\/) {$cl='(macro)';}
2984 else {$cl='(unidentified)';}
2985 return $cl;
2986 }
2987
2988 # Print table body containing word frequencies
2989 sub __print_sorted_freqs {
2990 my ($class,$Freq,$Word,$min)=@_;
2991 my $sum=0;
2992 my ($word,$wd,$freq);
2993 if (!defined $min) {$min=0;}
2994 if ($htmlstyle) {print "<tbody class='$class'>\n";}
2995 else {print "---\n";}
2996 for $wd (sort {$Freq->{$b} <=> $Freq->{$a}} keys %{$Freq}) {
2997 if (defined $Word) {$word=$Word->{$wd};} else {$word=$wd;}
2998 $freq=$Freq->{$wd};
2999 if ($freq>=$min) {
3000 $sum+=$freq;
3001 __print_word_freq($word,$freq);
3002 }
3003 }
3004 if ($min>0) {__print_word_freq('Sum of subset',$sum,'td','sum');}
3005 if ($htmlstyle) {print "</tbody>\n";}
3006 }
3007
3008 # Print one word freq line
3009 sub __print_word_freq {
3010 my ($word,$freq,$tag,$class)=@_;
3011 if (!defined $tag) {$tag='td';}
3012 if (defined $class) {$class=" class='$class'";} else {$class='';}
3013 if ($htmlstyle) {
3014 print "<tr$class><$tag>$word</$tag><$tag>$freq</$tag></tr>\n";
3015 } else {
3016 print $word,': ',$freq,"\n";
3017 }
3018 }
3019
3020 # Print macro usage statistics
3021 sub print_macro_stat {
3022 if ($htmlstyle) {print "<table class='stat'>\n<thead>\n";}
3023 __print_word_freq('Macro/envir','Freq','th');
3024 if ($htmlstyle) {print "</thead>\n";}
3025 if ($htmlstyle) {print "<tbody class='macrostat'>\n";}
3026 foreach my $name (sort keys %MacroUsage) {
3027 my $freq=$MacroUsage{$name};
3028 $name=text_to_printable($name);
3029 $name=text_to_print($name);
3030 if ($htmlstyle) {
3031 print "<tr><td>$name</td><td>$freq</td></tr>\n";
3032 } else {
3033 print $name,': ',$freq,"\n";
3034 }
3035 }
3036 if ($htmlstyle) {print "</tbody>\n";}
3037 if ($htmlstyle) {print "</table>\n";}
3038 }
3039
3040
3041
3042 ###### Printing routines
3043
3044
3045 # Print text using given style/colour
3046 sub print_with_style {
3047 my ($text,$style,$colour)=@_;
3048 if ($style eq $NOSTYLE) {
3049 print text_to_print($text);
3050 } elsif ($htmlstyle) {
3051 print "<span class='$style'>",text_to_print($text),'</span>';
3052 } else {
3053 ansiprint(text_to_print($text),$colour);
3054 if ($style=~/$separatorstyleregex/) {print $separator;}
3055 }
3056 }
3057
3058 # Prepare text string for print: convert special characters
3059 sub text_to_print {
3060 my $text=join('',@_);
3061 if ($htmlstyle) {
3062 $text=~s/&/&amp;/g;
3063 $text=~s/</&lt;/g;
3064 $text=~s/>/&gt;/g;
3065 $text=~s/[ \t]{2}/\&nbsp; /g;
3066 } elsif ($texcodeoutput) {
3067 $text=~s/\\/\\textbackslash¤/g;
3068 $text=~s/([%\{\}])/\\$1/g;
3069 $text=~s/¤/{}/g;
3070 }
3071 return $text;
3072 }
3073
3074 # Return &#xxx; code for character ;
3075 sub convert_to_charcode {
3076 my $ch=shift @_;
3077 return '&#'.ord($ch).';';
3078 }
3079
3080 # Convert special characters to charcodes to make it printable ;
3081 sub text_to_printable {
3082 my $text=shift @_;
3083 $text=~s/([^[:print:]])/convert_to_charcode($1)/gse;
3084 return $text;
3085 }
3086
3087 # Print text, using appropriate tags for HTML
3088 sub formatprint {
3089 my ($text,$tag,$class)=@_;
3090 my $break=($text=~s/(\r\n?|\n)$//);
3091 if ($htmlstyle && defined $tag) {
3092 print '<'.$tag;
3093 if ($class) {print " class='$class'";}
3094 print '>'.text_to_print($text)."</$tag>";
3095 } else {
3096 print text_to_print($text);
3097 }
3098 if ($break) {print "\n";}
3099 }
3100
3101 # Add a line break to output
3102 sub linebreak {
3103 if ($htmlstyle) {print "<br>\n";} else {print "\n";}
3104 }
3105
3106
3107 ###### Routines for printing count summary
3108
3109
3110 # Print count summary for a count object
3111 sub print_count {
3112 my ($count,$class,$title)=@_;
3113 line_return(0);
3114 if ($htmlstyle) {print "<div class='".($class||'count')."'>\n";}
3115 if (defined $title) {formatprint($title."\n",'h2');}
3116 if ($outputtemplate) {
3117 _print_count_template($count,$outputtemplate);
3118 } elsif ($briefsum && @sumweights) {
3119 _print_sum_count($count);
3120 } elsif ($briefsum) {
3121 if ($htmlstyle) {print "<p class='count'>";}
3122 _print_count_brief($count);
3123 if ($htmlstyle) {print "</p>\n";}
3124 } else {
3125 _print_count_details($count);
3126 }
3127 if ($htmlstyle) {print "</div>\n";}
3128 }
3129
3130 # Return count,header,... list filling in header if missing
3131 sub __count_and_header {
3132 my $count=shift @_;
3133 my $header=__count_header($count);
3134 return $count,$header,@_;
3135 }
3136
3137 # Return count title or '' if missing
3138 sub __count_header {
3139 my $count=shift @_;
3140 return $count->{'title'}||'';
3141 }
3142
3143 # Print total count (sum) for a given count object
3144 sub _print_sum_count {
3145 my ($count,$header)=__count_and_header(@_);
3146 if ($htmlstyle) {print "<p class='count'>".text_to_print($header).": ";}
3147 print get_sum_count($count);
3148 if ($htmlstyle) {print "</p>\n";}
3149 else {print ": ".text_to_print($header);}
3150 print "\n";
3151 }
3152
3153 # Print brief summary of count object
3154 sub _print_count_brief {
3155 my ($count,$header,$tag1,$tag2)=__count_and_header(@_);
3156 my @cnt=@{$count->{'counts'}};
3157 if ($htmlstyle && $tag1) {print '<',$tag1,'>';}
3158 print $cnt[$CNT_WORDS_TEXT],'+',$cnt[$CNT_WORDS_HEADER],'+',$cnt[$CNT_WORDS_OTHER];
3159 for (my $i=$SIZE_CNT_DEFAULT;$i<$SIZE_CNT;$i++) {
3160 if ($cnt[$i]) {print '+',$cnt[$i],$countkey[$i];}
3161 }
3162 print ' (',$cnt[$CNT_COUNT_HEADER],'/',$cnt[$CNT_COUNT_FLOAT],
3163 '/',$cnt[$CNT_COUNT_INLINEMATH],'/',$cnt[$CNT_COUNT_DISPLAYMATH],')';
3164 if ($htmlstyle && $tag2) {
3165 print '</',$tag1,'><',$tag2,'>';
3166 $tag1=$tag2;
3167 } else {print ' ';}
3168 print text_to_print($header);
3169 if ($htmlstyle && $tag1) {print '</',$tag1,'>';}
3170 if ($finalLineBreak) {print "\n";}
3171 }
3172
3173 # Print detailed summary of count object
3174 sub _print_count_details {
3175 my ($count,$header)=__count_and_header(@_);
3176 if ($htmlstyle) {print "<ul class='count'>\n";}
3177 if ($header) {formatprint($header."\n",'li','header');}
3178 if (my $tex=$count->{'TeXcode'}) {
3179 if (!defined $encoding) {formatprint('Encoding: '.$tex->{'encoding'}."\n",'li');}
3180 }
3181 if (@sumweights) {formatprint('Sum count: '.get_sum_count($count)."\n",'li');}
3182 for (my $i=1;$i<$SIZE_CNT;$i++) {
3183 formatprint($countdesc[$i].': '.get_count($count,$i)."\n",'li');
3184 }
3185 if (get_count($count,$CNT_FILE)>1) {
3186 formatprint($countdesc[$CNT_FILE].': '.get_count($count,$CNT_FILE)."\n",'li');
3187 }
3188 my $subcounts=$count->{'subcounts'};
3189 if ($showsubcounts && defined $subcounts && scalar(@{$subcounts})>=$showsubcounts) {
3190 formatprint("Subcounts:\n",'li');
3191 if ($htmlstyle) {print "<span class='subcount'>\n";}
3192 formatprint(" text+headers+captions (#headers/#floats/#inlines/#displayed)\n",'li','fielddesc');
3193 foreach my $subcount (@{$subcounts}) {
3194 print ' ';
3195 _print_count_brief($subcount,'li');
3196 }
3197 if ($htmlstyle) {print "</span>\n";}
3198 }
3199 if ($htmlstyle) {print "</ul>\n";} else {print "\n";}
3200 }
3201
3202 # Print summary of count object using template
3203 sub _print_count_template {
3204 my ($count,$header,$template)=__count_and_header(@_);
3205 $template=~s/\\n/\n/g;
3206 if ($htmlstyle) {$template=~s/\n/<br>/g;}
3207 my ($subtemplate,$posttemplate);
3208 while ($template=~/^(.*)\{SUB\?((.*?)\|)?(.*?)(\|(.*?))?\?SUB\}(.*)$/is) {
3209 __print_count_using_template($count,$1); # $1 ~ ${^PREMATCH}
3210 if (number_of_subcounts($count)>1) {
3211 if (defined $3) {print $3;}
3212 __print_subcounts_using_template($count,$4);
3213 if (defined $6) {print $6;}
3214 }
3215 $template=$7; # $7 ~ ${^POSTMATCH}
3216 }
3217 __print_count_using_template($count,$template);
3218 }
3219
3220 # Return string with counts based on template
3221 sub count_in_template {
3222 my ($count,$template)=@_;
3223 while (my ($key,$cnt)=each %key2cnt) {
3224 $template=__process_template($template,$key,get_count($count,$cnt));
3225 }
3226 $template=~s/\{VER\}/\Q$versionnumber\E/gi;
3227 $template=__process_template($template,'WARN|WARNING|WARNINGS',number_of_distinct_warnings($count));
3228 $template=__process_template($template,'NWARN|NWARNING|NWARNINGS',number_of_warnings($count));
3229 $template=__process_template($template,'ERR|ERROR|ERRORS',$count->{'errorcount'});
3230 $template=__process_template($template,'SUM',get_sum_count($count));
3231 $template=__process_template($template,'TITLE',$count->{'title'}||'');
3232 $template=__process_template($template,'SUB',number_of_subcounts($count));
3233 $template=~s/\a//gis;
3234 return $template;
3235 }
3236
3237 # Print counts using template
3238 sub __print_count_using_template {
3239 print count_in_template(@_);
3240 }
3241
3242 # Print subcounts using template
3243 sub __print_subcounts_using_template {
3244 my ($count,$template)=@_;
3245 my $subcounts=$count->{'subcounts'};
3246 if ($template && defined $subcounts && scalar(@{$subcounts})>=$showsubcounts) {
3247 foreach my $subcount (@{$subcounts}) {
3248 __print_count_using_template($subcount,$template);
3249 }
3250 }
3251 }
3252
3253 # Process template for specific label
3254 sub __process_template {
3255 my ($template,$label,$value)=@_;
3256 if ($value) {
3257 $template=~s/\{($label)\?(.*?)(\|(.*?))?\?(\1)\}/$2/gis;
3258 } else {
3259 $template=~s/\{($label)\?(.*?)\|(.*?)\?(\1)\}/$3/gis;
3260 $template=~s/\{($label)\?(.*?)\?(\1)\}//gis;
3261 }
3262 if (!defined $value) {$value='';}
3263 $template=~s/\{($label)\}/$value\a/gis;
3264 return $template;
3265 }
3266
3267
3268
3269 ###### Routines for printing parsing details
3270
3271
3272 # Print next token
3273 sub flush_next {
3274 my ($tex,$style)=@_;
3275 my $ret=undef;
3276 if (defined $style) {set_style($tex,$style);}
3277 if (defined $tex->{'next'}) {
3278 $ret=print_style($tex->{'next'},$tex->{'style'},$tex->{'printstate'});
3279 }
3280 $tex->{'printstate'}=undef;
3281 $tex->{'style'}=$STYLE_BLOCK;
3282 return $ret;
3283 }
3284
3285 # Print next token and gobble following spaces (incl. line break and comments)
3286 sub flush_next_gobble_space {
3287 my ($tex,$style,$state)=@_;
3288 my $ret=flush_next($tex,$style);
3289 if (!defined $ret) {$ret=0;}
3290 if (!defined $state) {$state=$STATE_IGNORE;}
3291 my $prt=($printlevel>0);
3292 while (1) {
3293 if ($tex->{'line'}=~s/^([ \t\f]*)(\r\n|\r|\n)([ \t\f]*)//) {
3294 if (!$prt) {
3295 } elsif ($printlevel>1 || $ret) {
3296 print $1;
3297 line_return(-1,$tex);
3298 my $space=$3;
3299 if ($htmlstyle) {$space=~s/ /\&nbsp;/g;}
3300 print $space;
3301 $ret=0;
3302 } else {
3303 line_return(0,$tex);
3304 }
3305 } elsif ($tex->{'line'}=~s/^([ \t\f]+)//) {
3306 if ($prt) {print $1;}
3307 }
3308 if ($tex->{'line'}=~/^\%TC:/i) {return;}
3309 if ($tex->{'line'}=~s/^(\%+[^\r\n]*)//) {
3310 print_style($1,'comment');
3311 $ret=1;
3312 } else {return;}
3313 }
3314 }
3315
3316 # Set presentation style
3317 sub set_style {
3318 my ($tex,$style)=@_;
3319 if (!(defined $tex->{'style'} && $tex->{'style'} eq $STYLE_BLOCK)) {$tex->{'style'}=$style;}
3320 }
3321
3322 # Print text using the given style, and log state if given
3323 sub print_style {
3324 my ($text,$style,$state)=@_;
3325 (($printlevel>=0) && (defined $text) && (defined $style)) || return 0;
3326 my $colour;
3327 ($colour=$STYLE{$style}) || return;
3328 if (defined $colour && $colour ne '-') {
3329 print_with_style($text,$style,$colour);
3330 if (defined $state) {print_style($state,'state');}
3331 if ($style ne 'cumsum') {$blankline=-1;}
3332 return 1;
3333 } else {
3334 return 0;
3335 }
3336 }
3337
3338 # Conditional line return
3339 sub line_return {
3340 my ($blank,$tex)=@_;
3341 if ($blank<0 && $printlevel<2) {$blank=1;}
3342 if ($blank<0 || $blank>$blankline) {
3343 if ((defined $tex) && @sumweights) {
3344 my $num=get_sum_count($tex->{'subcount'});
3345 print_style(" [$num]",'cumsum');
3346 }
3347 linebreak();
3348 $blankline++;
3349 }
3350 }
3351
3352
3353 ###### Print help on style/colour codes
3354
3355
3356 # Print output style codes if conditions are met
3357 sub conditional_print_style_list {
3358 if ($showcodes) {_print_style_list();}
3359 return $showcodes;
3360 }
3361
3362 # Print help on output styles
3363 sub _print_style_list {
3364 if ($printlevel<=0) {return;}
3365 if ($htmlstyle) {print '<div class="stylehelp"><p>';}
3366 formatprint('Format/colour codes of verbose output:','h2');
3367 print "\n\n";
3368 foreach my $style (@STYLE_LIST) {
3369 my $desc=$STYLE_DESC{$style};
3370 if ($desc=~/^(.*):\s+(.*)$/) {
3371 _help_style_line($1,$style,$2); # $1~${^PREMATCH}, $2~${^POSTMATCH}
3372 } else {
3373 _help_style_line($desc,$style);
3374 }
3375 }
3376 if ($htmlstyle) {print '</p></div>';}
3377 print "\n\n";
3378 }
3379
3380 # Print one line of help
3381 sub _help_style_line {
3382 my ($text,$style,$comment)=@_;
3383 if (!defined $comment) {$comment='';}
3384 if ($htmlstyle) {$comment='&nbsp;&nbsp;....&nbsp;&nbsp;'.text_to_print($comment);}
3385 else {$comment=' .... '.$comment;}
3386 if (print_style($text,$style)) {
3387 print $comment;
3388 linebreak();
3389 }
3390 }
3391
3392
3393 ###### Help routines
3394
3395
3396 # Print TeXcount version
3397 sub print_version {
3398 wprintstringdata('Version');
3399 }
3400
3401 # Print TeXcount licence text
3402 sub print_license {
3403 wprintstringdata('License');
3404 }
3405
3406 # Print short TeXcount help
3407 sub print_help {
3408 wprintstringdata('ShortHelp');
3409 }
3410
3411 # Print main TeXcount help
3412 sub print_help_man {
3413 wprintstringdata('HelpTitle');
3414 wprintstringdata('HelpText');
3415 wprintstringdata('Reference');
3416 }
3417
3418 # Print help on TC instructions
3419 sub print_help_tcinst {
3420 wprintstringdata('TCinstructions');
3421 }
3422
3423 # Print TeXcount options list
3424 sub print_help_options {
3425 wprintstringdata('OptionsHead');
3426 wprintstringdata('Options',StringDatum('OptionsFormat'));
3427 }
3428
3429 # Print TeXcount options containing substring
3430 sub print_help_options_subset {
3431 my $pattern=shift @_;
3432 my $data=StringData('Options');
3433 if (!defined $data) {
3434 error($Main,'No StringData Options.','BUG');
3435 return;
3436 }
3437 my @options;
3438 foreach (@$data) {
3439 if (/^\s*([^\s]+\s)*[^\s]*\Q$pattern\E/) {push @options,$_;}
3440 }
3441 if (scalar(@options)==0) {print "No options contained $pattern.\n";}
3442 else {
3443 print "Options containing \"$pattern\":\n\n";
3444 wprintlines(StringDatum('OptionsFormat'),@options);
3445 }
3446 }
3447
3448 # Print help on specific macro or environment
3449 sub print_help_on_rule {
3450 my $arg=shift @_;
3451 my $def;
3452 my %rules=(
3453 '\documentclass' => 'Initiates LaTeX document preamble.',
3454 '\begin' => 'Treatmend depends on environment handling rules.',
3455 '\def' => 'Excluded from count.',
3456 '\verb' => 'Strong exclude for enclosed region.',
3457 '$' => 'Opens or closes inlined equation',
3458 '$$' => 'Opens or closes displayed equation.',
3459 '\(' => 'Opens inlined equation.',
3460 '\)' => 'Closes inlined equation initiated by \(.',
3461 '\[' => 'Opens displayed equation.',
3462 '\]' => 'Closes displayed equation initiated by \[.');
3463 if (!defined $arg || $arg=~/^\s*$/) {
3464 print "\nSpecify macro or environment name after the -h= option.\n";
3465 return;
3466 }
3467 if ($arg=~/^[\w\-\%]+:/) {
3468 remove_all_rules();
3469 %rules=();
3470 while ($arg=~s/^([\w\-\%]+)://) {include_package($1);}
3471 }
3472 if ($def=$rules{$arg}) {
3473 print "\nSpecial rule (hard coded) for $arg\n";
3474 print $def."\n";
3475 } elsif ($arg=~/^\\/) {
3476 my $hasrule=0;
3477 print "\nRule(s) for macro $arg\n";
3478 if ($def=$TeXmacrocount{$arg}) {
3479 $hasrule=1;
3480 }
3481 if ($def=$TeXfileinclude{$arg}) {
3482 $hasrule=1;
3483 print "Takes file name as parameter which is included in document.\n";
3484 }
3485 if ($def=$TeXmacro{$arg}) {
3486 $hasrule=1;
3487 _print_rule_macro($arg,$def);
3488 }
3489 if ($def=$TeXfloatinc{$arg}) {
3490 $hasrule=1;
3491 print "\nIncluded inside floats:\n";
3492 _print_rule_macro($arg,$def);
3493 }
3494 if (!$hasrule) {
3495 print "\nNo macro rule defined for $arg.\nParameters treated as surrounding text.\n";
3496 }
3497 } else {
3498 if ($def=$TeXenvir{$arg}) {
3499 print "\nRule for environment $arg\n";
3500 _print_rule_macrocount($PREFIX_ENVIR.$arg);
3501 _print_rule_envir($arg,$def);
3502 } else {
3503 print "\nNo default environment rule defined for $arg.\nContent handled as surrounding text.\n";
3504 }
3505 }
3506 }
3507
3508 # Print macro handling rule
3509 sub _print_rule_macro {
3510 my ($arg,$def)=@_;
3511 if (!defined $def) {
3512 print "Takes no parameter(s).\n";
3513 } elsif (ref($def) eq 'ARRAY') {
3514 my $optionflag=0;
3515 print "Takes has the following parameters and parameter rules:\n";
3516 foreach my $state (@{$def}) {
3517 if ($state==$_STATE_OPTION) {$optionflag=1;}
3518 elsif ($state==$_STATE_NOOPTION) {print " - no [] options permitted here\n";}
3519 elsif ($state==$_STATE_AUTOOPTION) {}
3520 elsif ($optionflag) {
3521 $optionflag=0;
3522 print " + optional [] containing $state2desc{$state}\n";
3523 } else {
3524 print " + $state2desc{$state}\n";
3525 }
3526 }
3527 } else {
3528 print "Takes $def parameter(s): content ignored, i.e. not included in counts.\n";
3529 }
3530 }
3531
3532 # Print environment handling rule
3533 sub _print_rule_envir {
3534 my ($arg,$def)=@_;
3535 print "Contents parsed as $state2desc{$def}\n";
3536 if ($def=$TeXmacro{$PREFIX_ENVIR.$arg}) {
3537 _print_rule_macro($arg,$def);
3538 } else {
3539 print "Takes no parameter(s).\n";
3540 }
3541 }
3542
3543 # Print macrocount rule, return rule
3544 sub _print_rule_macrocount {
3545 my $arg=shift @_;
3546 my $def=$TeXmacrocount{$arg};
3547 if (!defined $def) {return undef;}
3548 if (ref($def) eq 'ARRAY') {
3549 my @wd=@$def;
3550 foreach (@wd) {$_=$countdesc[$_];}
3551 print 'Increments the following counters: ',join('; ',@wd),".\n";
3552 } else {
3553 print "Counted as $def word(s).\n";
3554 }
3555 }
3556
3557 # Print style or style category summary
3558 sub print_help_on_styles {
3559 my $style=shift @_;
3560 if (defined $style) {
3561 if (my $def=$STYLES{$style}) {
3562 _print_help_on_style_category($style);
3563 print wrap('',' ',"$style = ".join(', ',grep(/^\w+$/,sort keys %$def))),".\n";
3564 } elsif ($def=$STYLE_DESC{$style}) {
3565 print $style,' = ',$def,"\n";
3566 } else {
3567 print "Unknown style or style category: $style.\n";
3568 }
3569 } else {
3570 print wrap('',' ','Styles: '.join(', ',@STYLE_LIST)),".\n\n";
3571 print wrap('',' ','Style categories: '.join(', ',sort grep(/^\w+$/,keys %STYLES))),".\n\n";
3572 print "Use -help-style={style} to get help on particular style or style category.\n";
3573 }
3574 }
3575
3576 # Print help on a particular style category (optional prefix and indentation)
3577 sub _print_help_on_style_category {
3578 my ($cat,$prefix,$indent)=@_;
3579 if (!defined $prefix) {$prefix='';}
3580 if (!defined $indent) {$indent=' ';}
3581 }
3582
3583
3584 ###### HTML routines
3585
3586
3587 # Print HTML header
3588 sub html_head {
3589 if (defined $HTMLfile) {
3590 if (open(FH,$HTMLfile)) {
3591 my $text=join('',<FH>);
3592 close FH;
3593 if ( $text=~/^(.*)<!--+\s*texcount\s*--+>(.*)$/is
3594 || $text=~/^(.*)\$\{texcount\}(.*)$/is
3595 || $text=~/^(.*)(<\/body.*)$/is
3596 ) {
3597 $htmlopen=$1;
3598 $htmlclose=$2;
3599 } else {
3600 error($Main,"Invalid HTML template format.");
3601 }
3602 } else {
3603 error($Main,"HTML template file not found: $HTMLfile");
3604 }
3605 }
3606 if (defined $htmlopen) {
3607 $htmlopen=~s/\$\{encoding\}/\Q$outputEncoding\E/g;
3608 $htmlopen=~s/\$\{version\}/@{[_html_version()]}/g;
3609 print $htmlopen;
3610 $htmlopen=undef;
3611 } else {
3612 print "<html>\n<head>\n";
3613 print "<meta http-equiv='content-type' content='text/html; charset=$outputEncoding'>\n";
3614 _print_html_style();
3615 foreach (@htmlhead) {print $_,"\n";}
3616 print "</head>\n\n<body>\n";
3617 print "\n<h1>LaTeX word count";
3618 if ($showVersion>0) {print ' (version ',_html_version(),')'}
3619 print "</h1>\n";
3620 }
3621 }
3622
3623 # Print HTML tail
3624 sub html_tail {
3625 if (defined $htmlclose) {
3626 print $htmlclose;
3627 $htmlclose=undef;
3628 } else {
3629 print "</body>\n\n</html>\n";
3630 }
3631 }
3632
3633 # Return version number using HTML
3634 sub _html_version {
3635 my $htmlver=$versionnumber;
3636 $htmlver=~s/\b(alpha|beta)\b/&$1;/g;
3637 return $htmlver;
3638 }
3639
3640 # Print HTML STYLE element
3641 sub _print_html_style {
3642 if (defined $CSShref) {
3643 print "<link rel='stylesheet' href='$CSShref' type='text/css'>\n";
3644 return;
3645 }
3646 if (defined $CSSfile) {
3647 if (open(FH,$CSSfile)) {
3648 print "<style>\n<!---\n",<FH>,"-->\n</style>\n";
3649 close(FH);
3650 return;
3651 } else {
3652 error($Main,"CSS file not found: $CSSfile");
3653 }
3654 }
3655 print <<END
3656 <style>
3657 <!--
3658 body {width:auto;padding:5;margin:5;}
3659 .error {font-weight:bold;color:#f00;font-style:italic; border: solid 1px red;}
3660 .word,.hword,.oword,.altwd {border-left: 1px solid #CDF; border-bottom: 1px solid #CDF;}
3661 .word {color: #009}
3662 .hword {color: #009; font-weight: 700;}
3663 .oword {color: #009; font-style: italic;}
3664 .altwd {color: #00c; font-style: oblique;}
3665 .cmd {color: #c00;}
3666 .exclcmd {color: #f99;}
3667 .option {color: #cc0;}
3668 .optparm {color: #c90;}
3669 .envir, .document {color: #900; font-weight:bold;}
3670 .math {color: #6c0;}
3671 .mathgroup {color: #090;}
3672 .exclmath {color: #9f6;}
3673 .mathcmd {color: #6c0;}
3674 .ignore {color: #999;}
3675 .exclenv {color:#c66;}
3676 .special {color:#c66; font-weight: bold;}
3677 .specarg {color:#c66; font-weight: bold; font-style: italic;}
3678 .tc {color: #999; font-weight:bold;}
3679 .comment {color: #999; font-style: italic;}
3680 .state {color: #990; font-size: 70%;}
3681 .cumsum {color: #999; font-size: 80%;}
3682 .fileinc {color: #696; font-weight:bold;}
3683 .warning {color: #c00; font-weight: 700;}
3684 .note {color: #c90; font-weight: bold;}
3685
3686 div.filegroup, div.parse, div.stylehelp, div.count, div.sumcount, div.error {
3687 border: solid 1px #999; margin: 4pt 0pt; padding: 4pt;
3688 }
3689 div.stylehelp {font-size: 80%; background: #fffff0; margin-bottom: 16pt;}
3690 div.filegroup {background: #dfd; margin-bottom: 16pt;}
3691 div.count {background: #ffe;}
3692 div.sumcount {background: #cec;}
3693 div.error {background: #fcc;}
3694 .parse {font-size: 80%; background: #f8fff8; border-bottom:none;}
3695
3696 ul.count {list-style-type: none; margin: 4pt 0pt; padding: 0pt;}
3697 .count li.header {font-weight: bold; font-style: italic;}
3698 .subcount li.header {font-weight: normal; font-style: italic;}
3699 .subcount li {margin-left: 16pt; font-size: 80%;}
3700 .fielddesc {font-style: italic;}
3701 .nb {color: #900;}
3702
3703 table.stat {border:2px solid #339; margin:0 0 8pt 0; background:#666; border-collapse:collapse;}
3704 table.stat tr {border:1px solid #CCC;}
3705 table.stat th, table.stat td {padding:1pt 4pt;}
3706 table.stat col {padding:4pt;}
3707 table.stat thead {background: #CCF;}
3708 table.stat tbody {border:1px solid #333;}
3709 table.stat tbody.sumstat {background:#FFC;}
3710 table.stat tbody.langstat {background:#FEE;}
3711 table.stat tbody.wordstat {background:#EEF;}
3712 table.stat tbody.macrostat {background:#EFE;}
3713 table.stat .sum {font-weight:bold; font-style:italic;}
3714 -->
3715 </style>
3716 END
3717 }
3718
3719
3720 ###### Read text data
3721
3722
3723
3724 # Return the STRINGDATA hash (lazy instantiation)
3725 sub STRINGDATA {
3726 if (!defined $STRINGDATA) {
3727 my @DATA=<DATA>;
3728 foreach (@DATA) {
3729 $_=~s/\$\{(\w+)\}/__apply_globaldata($1)/ge;
3730 }
3731 $STRINGDATA=splitlines(':{3,}\s*(\w+)?',\@DATA);
3732 }
3733 return $STRINGDATA;
3734 }
3735
3736 # Return value from STRINGDATA hash
3737 sub StringData {
3738 my $name=shift @_;
3739 return STRINGDATA()->{$name};
3740 }
3741
3742 # First line of StringData
3743 sub StringDatum {
3744 return pop @{StringData(@_)};
3745 }
3746
3747 # Insert value from GLOBALDATA
3748 sub __apply_globaldata {
3749 my $name=shift @_;
3750 if (my $value=$GLOBALDATA{$name}) {
3751 return $value;
3752 }
3753 return '[['.$name.']]';
3754 }
3755
3756 # Print value from STRINGDATA using wprintlines
3757 sub wprintstringdata {
3758 my $name=shift @_;
3759 my $data=StringData($name);
3760 if (!defined $data) {
3761 error($Main,"No StringData $name.",'BUG');
3762 return;
3763 }
3764 wprintlines(@_,@$data);
3765 }
3766
3767 # Divide array of lines by identifying headers
3768 sub splitlines {
3769 my ($pattern,$lines)=@_;
3770 if (!defined $lines) {return;}
3771 my $id=undef;
3772 my %hash;
3773 foreach my $line (@$lines) {
3774 if ($line=~/^$pattern$/) {
3775 $id=$1;
3776 if (defined $id) {
3777 $hash{$id}=[];
3778 if (defined $2) {push @{$hash{$id}},$2;}
3779 }
3780 } elsif (defined $id) {
3781 chomp $line;
3782 push @{$hash{$id}},$line;
3783 }
3784 }
3785 return \%hash;
3786 }
3787
3788 # Print string with word wrapping and indentation using
3789 # wprintlines.
3790 sub wprint {
3791 my $text=shift @_;
3792 my @lines=split(/\n/,$text);
3793 wprintlines(@lines);
3794 }
3795
3796 # Print with word wrapping and indentation. A line with
3797 # @ - :
3798 # sets two column tabs. A tab or multiple spaces is taken
3799 # to indicate indentation. If the first column value is
3800 # only a single '|', this is just an indication to skip
3801 # one tab.
3802 sub wprintlines {
3803 my @lines=@_;
3804 my $ind1=2;
3805 my $ind2=6;
3806 my $i;
3807 foreach my $line (@lines) {
3808 if ($line=~s/^@/ /) {
3809 $ind1=index($line,'-');
3810 $ind2=index($line,':');
3811 if ($ind1<1) {$ind1=$ind2;}
3812 next;
3813 }
3814 my $firstindent=0;
3815 if ($line=~s/^(\t|\s{2,})(\S)/$2/) {$firstindent=$ind1;}
3816 my $indent=$firstindent;
3817 if ($line=~/^(.*?\S)(\t|\s{2,})(.*)$/) {
3818 $indent=$ind2;
3819 if ($1 eq '|') {$line=' ';}
3820 else {$line=$1.' ';}
3821 $i=$indent-$firstindent-length($line);
3822 if ($i>0) {$line.=' ' x $i;}
3823 $line.=$3; # $3~${^POSTMATCH}
3824 }
3825 print wrap(' ' x $firstindent,' ' x $indent,$line)."\n";
3826 }
3827 }
3828
3829
3830 ########################################
3831 ##### TEXT DATA
3832
3833 __DATA__
3834
3835
3836 ::::::::::::::::::::::::::::::::::::::::
3837 :::::::::: Version
3838 TeXcount version ${versionnumber}, ${versiondate}.
3839
3840 :::::::::: Reference
3841 Go to the TeXcount web page
3842 ${website}
3843 for more help and information about the script: news, updates, help, usage tips, known issues and short-comings, or to access the script as a web application. Feedback such as problems or errors can be reported to [email protected].
3844
3845 The TeXcount script is copyright of ${maintainer} (${copyrightyears}) and published under the LaTeX Project Public Licence.
3846
3847 :::::::::: License
3848 TeXcount version ${versionnumber}
3849
3850 Copyright ${copyrightyears} ${maintainer}
3851
3852 The TeXcount script is published under the LaTeX Project Public License (LPPL)
3853 http://www.latex-project.org/lppl.txt
3854 which grants you, the user, the right to use, modify and distribute the script. However, if the script is modified, you must change its name or use other technical means to avoid confusion.
3855
3856 The script has LPPL status "maintained" with ${maintainer} being the current maintainer.
3857
3858 ::::::::::::::::::::::::::::::::::::::::
3859 :::::::::: ShortHelp
3860 Syntax: texcount.pl [options] files
3861
3862 Use option -help (or just -h) to get help. For more detailed help, the following alternatives exist:
3863 @ - :
3864 -help-man, -man Manual with more extensive help
3865 -help-rule={macro/envir} Macro/environment handling rule (backslash needed with macros)
3866 -help-options (-hopt) Get list of command line options
3867 -help-options={substring} Help on options containing substring
3868 -help-styles List styles which determine how different elements (words, macros, etc) are presented in the verbose output
3869 -help-style={style} Describe a particular style or style category
3870 -help-tc, -help-instructions Help on %TC:instruction for inserting TeXcount instructions into the TeX code.
3871
3872 Help, documentation, FAQ and updates are available from the TeXcount web page:
3873 ${website}
3874 or through running
3875 texdoc texcount
3876 on the command line.
3877
3878 ::::::::::::::::::::::::::::::::::::::::
3879 :::::::::: HelpTitle
3880 ***************************************************************
3881 * TeXcount version ${versionnumber}, ${versiondate}
3882 *
3883
3884 Count words in TeX and LaTeX files, ignoring macros, tables, formulae, etc.
3885
3886 ::::::::::::::::::::::::::::::::::::::::
3887 :::::::::: HelpText
3888 The script counts words as either words in the text, words in headers/titles or words in floats (figure/table captions). Macro options (i.e. \\macro[...]) are ignored; macro parameters (i.e. \\macro{...}) are counted or ignored depending on the macro, but by default counted. Begin-end groups are by default ignored and treated as 'floats', though some (e.g. center) are counted.
3889
3890 Mathematical formulae are not counted as words, but are instead counted separately with separate counts for inlined formulae and displayed formulae. Similarly, the number of headers and the number of 'floats' are counted. Note that 'float' is used here to describe anything defined in a begin-end group unless explicitly recognized as text or mathematics.
3891
3892 The verbose options (-v1, -v2, -v3, showstate) produces output indicating how the text has been interpreted. Check this to ensure that words in the text has been interpreted as such, whereas mathematical formulae and text/non-text in begin-end groups have been correctly interpreted.
3893
3894 Summary, as well as the verbose output, may be produced as text (default) or as HTML code using the -html option. The HTML may then be sent to file which may be viewed with you favourite browser.
3895
3896 Under UNIX, unless -nocol (or -nc) has been specified, the output will be colour coded using ANSI colour codes. Counted text is coloured blue with headers are in bold and in HTML output caption text is italicised. Use 'less -r' instead of just 'less' to view output: the '-r' option makes less treat text formating codes properly. Windows does not support ANSI colour codes, and so this is turned off by default.
3897
3898 ::::::::::::::::::::::::::::::::::::::::
3899 :::::::::: OptionsHead
3900
3901 Syntax: texcount.pl [options] files
3902
3903 Options:
3904
3905 :::::::::: OptionsFormat
3906 @ - :
3907 :::::::::: Options
3908 -relaxed Uses relaxed rules for word and option handling: i.e. allows more general cases to be counted as either words or macros.
3909 -restricted Restricts the rules for word and option handling.
3910 -v Verbose (same as -v3).
3911 -v0 Do not present parsing details.
3912 -v1 Verbose: print parsed words, mark formulae.
3913 -v2 More verbose: also print ignored text.
3914 -v3 Even more verbose: include comments and options.
3915 -v4 Same as -v3 -showstate.
3916 -v=, v0=, ..., -v4= Set verbosity by adding/removing particular types of token (styles) to include in the verbose output. Use -help-style to get details of which tokens are included in each style, and of classes of tokens (style categories).
3917 -showstate Show internal states (with verbose).
3918 -brief Only prints a brief, one line summary of counts.
3919 -q, -quiet Quiet mode, no error messages. Use is discouraged!
3920 -strict Strict mode, warns against begin-end groups for which rule are not defined.
3921 -sum, -sum= Make sum of all word and equation counts. May also use -sum=#[,#] with up to 7 numbers to indicate how each of the counts (text words, header words, caption words, #headers, #floats, #inlined formulae, #displayed formulae) are summed. The default sum (if only -sum is used) is the same as -sum=1,1,1,0,0,1,1.
3922 -nosum Do not compute sum.
3923 -sub, -sub= Generate subcounts. Option values are none, part, chapter, section or subsection. Default (-sub) is set to subsection, whereas unset is none. (Alternative option name is -subcount.)
3924 -nosub Do not generate subcounts.
3925 -col Use ANSI colours in text output.
3926 -nc, -nocol No colours (colours require ANSI).
3927 -nosep, -noseparator No separating character/string added after each word (default).
3928 -sep=, -separator= Separating character or string to be added after each word.
3929 -html Output in HTML format.
3930 -htmlcore Only HTML body contents.
3931 -htmlfile= HTML template file to use with the -html option. Use <!-- TeXcode --> to indicate where the output from TeXcount should be inserted.
3932 -tex Encode TeX special characters for output into TeX code
3933 -cssfile= CSS file to include instead of default styles.
3934 -css= CSS href to include instead of default styles. Can use -css=file:{filename} instead of -cssfile={filename}.
3935 -opt=, -optionfile= Read options/parameters from file.
3936 - Read LaTeX code from STDIN.
3937 -inc Parse included TeX files (as separate file).
3938 -merge Merge included TeX files into code (in place).
3939 -noinc Do not include included tex files (default).
3940 -incbib Include bibliography in count, include bbl file if needed.
3941 -nobib Do not include bibliography in count (default).
3942 -incpackage= Include rules for the given package.
3943 -total Do not give sums per file, only total sum.
3944 -1 Same as -brief and -total. Ensures there is only one line of output. If used in conjunction with -sum, the output will only be the total number. (NB: Character is the number one, not the letter L.)
3945 -template= Speficy an output template. Use {1},...,{7}, {SUM} and {TITLE} to include values, {1?...?1} etc. to conditionally include sections, {1?....|...?1} etc. to specify an alternative text if zero. To include subcounts, use {SUB?...?SUB} where ... is replaced with the template to use per subcount. Line shift may be specified using \\n.
3946 -dir, -dir= Specify the working directory using -dir=path. Remember that the path must end with \\ or /. If only -dir is used, the directory of the provided file is used and paths (e.g. included files) are assumed to be absolute or relative to this. The default at startup is -dir=. which means that the directory from which TeXcount is run is the working directory with all paths absolute or relative to this.
3947 -auxdir, -auxdir= Specify directory for auxilary files, e.g. the bibliograph (.bbl) file. If only -auxdir is used, the working directory (as determined by -dir or -dir=) is assumed. If -auxdir= is used with -dir=, it sets the path to the auxilary directiry. If -auxdir= is used with -dir, the working directory is determined from the location of the provided file, and the path to the auxilary directory is assumed to be absolute or relative to this.
3948 -enc=, -encoding= Specify encoding (default is to guess the encoding).
3949 -utf8, -unicode Selects Unicode (UTF-8) for input and output. This is automatic with -chinese, and is required to handle e.g. Korean text. Note that the TeX file must be save in UTF-8 format (not e.g. GB2312 or Big5), or the result will be unpredictable.
3950 -alpha=, -alphabets= List of Unicode character groups (or digit, alphabetic) permitted as letters. Names are separated by ',' or '+'. If list starts with '+', the alphabets will be added to those already included. The default is Digit+alphabetic.
3951 -logo=, -logograms= List of Unicode character groups interpreted as whole word characters, e.g. Han for Chinese characters. Names are separated by ',' or '+'. If list starts with '+', the alphabets will be added to those already included. By default, this is set to include Ideographic, Katakana, Hiragana, Thai and Lao.
3952 -ch, -chinese, -zhongwen Turns on support for Chinese characters. TeXcount will then count each Chinese character as a word.
3953 -jp, -japanese Turns on support for Japanese characters. TeXcount will count each Japanese character (kanji, hiragana, and katakana) as one word, i.e. not do any form of word segmentation.
3954 -kr, -korean Turns on support for Korean. This will count hangul and han characters, i.e. with no word separation. NB: Experimental!
3955 -kr-words, -korean-words Turns on support for Korean words, i.e. hangul words separated by characters. Han characters are still counted as characters. NB: Experimental!
3956 -ch-only, ..., -korean-words-only As options -chinese, ..., -korean-words, but also excludes letter-based words or trims down the character set to the minimum.
3957 -char, -character, -letters Counts letters/characters instead of words. Note that spaces and punctuation is not counted.
3958 -char-only, ..., -letters-only Like -letters, but counts alphabetic letters only.
3959 -countall, -count-all The default setting in which all characters are included as either alphabets og logograms.
3960 -freq, -freq= Produce individual word frequency table. Optionally give minimal number of occurences to be listed.
3961 -stat Produce statistics on language/script usage.
3962 -macrostat, -macrofreq Print macro usage statistics.
3963 -codes Display output style code overview and explanation. This is on by default.
3964 -nocodes Do not display output style code overview.
3965 -out= Write output to file, give filename as option value.
3966 -out-stderr Write output to STDERR instead of STDOUT.
3967 -h, -?, -help, /? Help text.
3968 -help-man, -man Short manual.
3969 -h=, -help-rule= Takes a macro or group name as option and returns a description of the rules for handling this if any are defined. If handling rule is package specific, use -incpackage=package name: -incpackage must come before -h= on the command line to take effect.
3970 -help-options, -h-opt List all options.
3971 -help-options=, -h-opt= List all options containing the provided string, e.g. -h-opt=dir or -h-opt=-v (the initial - in -v causes only options starting with v to be listed).
3972 -help-tc, -help-inst List all TeXcount instructions insertable as %TC comments in the TeX document.
3973 -help-style List the styles and style categories: i.e. those permitted used with -v={styles-list}.
3974 -help-style= Give description of style or style category.
3975 -ver, -version Print version number.
3976 -lic, -license, -licence Licence information.
3977
3978 ::::::::::::::::::::::::::::::::::::::::
3979 :::::::::: TCinstructions
3980 Parsing instructions may be passed to TeXcount using comments in the LaTeX files on the format
3981 @ - :
3982 %TC:instruction arguments
3983 and are used to control how TeXcount parses the document. The following instructions are used to set parsing rules which will apply to all subsequent parsing (including other files):
3984 %TC:macro [macro] [param.states]
3985 | macro handling rule, no. of and rules for parameters
3986 %TC:macrocount [macro] [number]
3987 | macro counted as a given number of words (alternative: %TC:macroword)
3988 %TC:header [macro] [param.states]
3989 | header macro rule, as macro but counts as one header (deprecated, use instead: %TC:macro \macro [header])
3990 %TC:breakmacro [macro] [label]
3991 | macro causing subcount break point
3992 %TC:envir [name] [param.states] [content-state]
3993 | \begin-\end environment handling rule (alternative: %TC:group)
3994 %TC:floatinclude [macro] [param.states]
3995 | as macro, but also counted inside floats
3996 %TC:preambleinclude [macro] [param.states]
3997 | as macro, but also counted inside the preamble
3998 %TC:fileinclue [macro] [rule]
3999 | file include, add .tex if rule=2, not if rule=0, if missing when rule=1
4000 The [param.states] is used to indicate the number of parameters used by the macro and the rules of handling each of these: the format is [#,#,...,#] with # representing one number for each parameter giving the parsing state to use for that parameter, alternatively just a single number (#) indicating how many parameters to ignore (parsing state 0). The option [content-state] is used to give the parsing state to use for the contents of a begin-end group. The main parsing states are 0 to ignore and 1 to count as text.
4001
4002 Parsing instructions which may be used anywhere are:
4003 @ - :
4004 %TC:break [title] add subcount break point here
4005 %TC:incbib include bibliography (same as running with -incbib)
4006 %TC:ignore ignore region, end with %TC:endignore
4007 %TC:insert [code] insert code for TeXcount to process as TeX code
4008 %TC:subst [from] [to] replace string thoughout document
4009 %TC:newtemplate start a new template, ie delete the existing one
4010 %TC:template [template] add another line to the template specification
4011 See the documentation for more details.
4012
4013 Command line options and most %TC commands (prefixed by % rather than %TC:) may be placed in an options file. This is particularly useful for defining your own output templates and macro handling rules.
4014
4015 ::::::::::::::::::::::::::::::::::::::::
4016
4017