NAME

LaTeX::Replicase - Perl extension implementing a minimalistic engine for filling real TeX-LaTeX files that act as templates.

SYNOPSIS

Activate the module:

use LaTeX::Replicase qw( replication );

or

use LaTeX::Replicase qw(:all);

Usage examples:

1. Using replication() with default options.

The following pseudo-code extract demonstrates this:

  • Fragment of the original (source) TeX file (or an array of strings, each of which is an element of this array) with fillable fields myParam, myArray, myHash, myTable_array, and myTable_hash:

    %%%TDZ:  %-- beginning of The Dead Zone
    \documentclass[10pt,a4paper]{article}
    \usepackage[english]{babel}
    \usepackage{amsmath}
    \usepackage{color}
    \usepackage{url}
    
    \title{ChiTaRS-${}_{3.1}$-the enhanced chimeric transcripts and RNA-seq database etc...}
    \author{Alessandro Gorohovski, etc...}
    
    \begin{document}
    \maketitle
    %%%ENDZ: -- end of The Dead Zone
    
    SPECIFY VALUE of myParam! %%%V: myParam  %-- substitutes SCALAR var
    
    etc...
    
    \begin{tcolorbox}
    \rule{0mm}{4.5em}%%%VAR: myParam -- substitutes SCALAR var as well
    ...
    ... SPECIFY VALUE of myParam!
    ...
    %%%END:
    \end{tcolorbox}
    
    %%%VAR: myParam %-- SCALAR substitution with support for internal ADD[E] tags
    \mbox{ %%%ADD:%
    \rule{0mm}{4.5em} %%%ADD:
    head \ldots %%%ADD:
    ... SPECIFY VALUE of myParam!
    tail \ldots %%%ADDE:%
    } %%%ADDE:
    %%%END:
    
    \begin{tabular}{%
    c
    %%%VAR: myArray
    l %%%ADD:%  -- column "l" type will repeat as many times as myArray size, e.g. 'lll...l'
    lllll
    %%%END:
    }
    % head of table
    Expense item &
    %%%VAR: myArray
    %-- eXcept 1st (0) row (record)
    %%%ADDX: &
    \multicolumn{1}{c}{ %%%ADD:%  -- there will be no line break
    % there will be no line break also
    2020 %%%V:@%
    } %%%ADDE:  -- final part of '@' variables
    & 2021 & 2022 & 2023 & 2024 & 2025  % All of this will be replaced until %%%END:
    %%%END:
    \\ \hline
    
    etc...
    
    \\ \hline
    HASH Summary
    %%%VAR: myHash
    & %%%ADD:
    00000 %%%V: year0
    & %%%ADD:
    11111 %%%V: year1
    & %%%ADD:
    22222 %%%V: year2%
     &  %%%ADD:%
    33333 %%%V: year3
    & 44444  &  55555
    %%%END:
    
    %%%VAR: myTable_array
    \\ \hline %%%ADD:
     SPECIFY VALUE 0!  %%%V:0
    &  %%%ADD:
    \multicolumn{1}{c}{ %%%ADD:% -- there will be no line break
     SPECIFY VALUES from 3 to last element of array! %%%V:3-%
    } %%%ADDE:
    & %%%ADD:%
     SPECIFY VALUES 1 and 2 %%%V:1,2
    &  22222  &  33333  & 44444  &  55555
    
    %%%TDZ: -- beginning of The Dead Zone. Yes, you can use this instead of %%%END:
    
    \\ \hline
    \end{tabular}
    ...
    \begin{tabular}{cccc}
     column2 & column1 & column0 \\\\
     \toprule
    %%%ENDZ: -- end of The Dead Zone
    
    %%%VAR: myTable_array
    SPECIFY VALUE 4 %%%V: 4
     & %%%ADD:%  % add " &" without line breaks ("\n")
    SPECIFY VALUES 2, 1, and 0! %%%V: -3-%
     & VALUE 1
     & VALUE 0
    \\ %%%ADD:
    \midrule %%%ADDX:
    ...
    VALUE 4 & VALUE 2 & VALUE 1 & VALUE 0
    \\
    \midrule
    ...
    %%%TDZ: %-- beginning of The Dead Zone.
    \end{tabular}
    ...
    \begin{tabbing}
    %%%ENDZ: -- end of The Dead Zone
    %%%VAR: myTable_hash
    %%%ADDX: \\\\
       SPECIFY VALUE 'A'! %%%V: A%
     \= %%%ADD:%
       SPECIFY VALUE 'B'! %%%V: B%
     \= %%%ADD:%
       SPECIFY VALUE 'C'! %%%V: C
    %%%ENDT: -- end of Template area (and myTable_hash also)
    \end{tabbing}
    
    etc...
    
    \end{document}
  • Dataset to fill TeX file (see above):

    my $info = {
         myParam => 'Blah-blah blah-blah blah-blah',
         myArray => [2024, 2025, 2026, 2027],
         myHash => {year0 => 123456, year1 => 789012, year2 => 345678, year3 => 901234},
         myTable_array => [ # custom user variable ARRAY-ARRAY
            ['00','01','02','03','04',], # row 0
            [10, 11, 12, 13, 14,], # row 1
            [20, 21, 22, 23, 24,], # row 2
         ],
         myTable_hash => [ # custom user variable ARRAY-HASH
           {A=>'00',B=>'01',C=>'02',}, # row 0
           {A=>10, B=>11, C=>12, }, # row 1
         ],
    };
    
    my $msg = replication( $file, $info );
  • Ready (filled, completed) TeX file (or the console output result, i.e. STDOUT):

    %-- beginning of The Dead Zone
    \documentclass[10pt,a4paper]{article}
    \usepackage[english]{babel}
    \usepackage{amsmath}
    \usepackage{color}
    \usepackage{url}
    
    \title{ChiTaRS-${}_{3.1}$-the enhanced chimeric transcripts and RNA-seq database etc...}
    \author{Alessandro Gorohovski, etc...}
    
    \begin{document}
    \maketitle
    
    Blah-blah blah-blah blah-blah %-- substitutes Variable
    
    etc...
    
    \begin{tcolorbox}
    \rule{0mm}{4.5em}Blah-blah blah-blah blah-blah-- substitutes Variable as well
    \end{tcolorbox}
    
    \mbox{\rule{0mm}{4.5em}
    head \ldots
    Blah-blah blah-blah blah-blah%-- SCALAR substitution with support for internal ADD[E] tags
    tail \ldots}
    
    \begin{tabular}{%
    c
    llll}
    % head of table
    Expense item &
    \multicolumn{1}{c}{2024}
    &
    \multicolumn{1}{c}{2025}
    &
    \multicolumn{1}{c}{2026}
    &
    \multicolumn{1}{c}{2027}
    \\ \hline
    
    etc...
    
    \\ \hline
    HASH Summary
    &
    123456
    &
    789012
    &
    345678 & 901234
    \\ \hline
    00
    & 
    \multicolumn{1}{c}{03}
    & 
    \multicolumn{1}{c}{04}
    &01
    &02
    \\ \hline
    10
    & 
    \multicolumn{1}{c}{13}
    & 
    \multicolumn{1}{c}{14}
    &11
    &12
    \\ \hline
    20
    & 
    \multicolumn{1}{c}{23}
    & 
    \multicolumn{1}{c}{24}
    &21
    &22
    \\ \hline
    \end{tabular}
    ...
    \begin{tabular}{cccc}
     column2 & column1 & column0 \\
     \toprule
    04
     &02 &01 &00\\
    \midrule
    14
     &12 &11 &10\\
    \midrule
    24
     &22 &21 &20\\
    \end{tabular}
    ...
    \begin{tabbing}
    00 \=01 \=02
    \\
    10 \=11 \=12
    \end{tabbing}
    etc...
    \end{document}

A new TeX base_file from the template $file (or $arr) filled with data from $info will be created in random subdirectory (its name is stored in $$ variable) of current directory. File name of source $file can be absolute, i.e. with a full path (include directories and subdirectories). base_file name is extracted (same) from source $file. Under no circumstances will source $file be overwritten by new base_file.

If the source is an array reference and no target file name is specified by ofile option, then ready.tex file will be created in a random subdirectory (its name is stored in $$ variable) of current directory.

2. Using outdir option:
my $target_dir = 'sandbox';
my $msg = replication( $file, $info, outdir => $target_dir );

A new $file will be created in $target_dir directory.

3. Using ofile option:
my $ofile = 'sandbox/ready_good.tex';
my $msg = replication( $file, $info, ofile => $ofile );

A new $ofile will be created. ofile option suppresses (eliminates) outdir option, i.e. file name of $ofile can be absolute. Under no circumstances will source $file be overwritten by new $ofile.

If the completed template (ready TeX) needs to be output directly to the console (or, for example, for the Web), you can specify:

ofile => *STDOUT

Of course, in this case outdir option will not be valid either.

4. Set the $DEBUG package variable to enable debugging messages (global debug mode):
$LaTeX::Replicase::DEBUG = 1;

LIMITATIONS

In a general sense, there are no restrictions on the complexity of $info structure. This is because you can point to the nested structure you need by redefining the global and/or local environment (see %%%V: and %%%VAR: tags below).

However, for populating TeX template with direct values (without regard to the nesting path), replication() supports only the following structures included in $info.

1. single-level:

SCALAR, REF, ARRAY, HASH, and their combinations, e.g.

my $v = 'Blah-blah';
my @ell = (11, 22, 33);

my $info = {
     Param => 'Blah-blah blah-blah',
     Ref => \$v,
     Array1 => [2025, 2026, 2027, 2028,],
     Array2 => [1..5],
     Array3 => \@ell,
     Array4 => [ \$ell[2], \$ell[0], \$ell[1], ],
     Hash => {year0 => 123456, year1 => 789012, year2 => 345678,},
     ...
};
2. two-level:

ARRAY.ARRAY, ARRAY.HASH, ARRAY.REF, HASH.ARRAY, and their combinations, e.g.

my $info = {
     Array_array => [ # custom user variable ARRAY-ARRAY
        ['00','01','02','03','04',], # row 0
        [10, 11, 12, 13, 14,], # row 1
        [20, 21, 22, 23, 24,], # row 2
        ...
     ],
     Array_hash => [ # variable ARRAY-HASH
        {A=>'00',B=>'01',C=>'02',}, # row 0
        {A=>10, B=>11, C=>12,}, # row 1
        ...
     ],
     Array_ref => [ # variable ARRAY-REF
        \@ell, # row 0
        \@ell, # row 1
        ...
     ],
     Array_mixed => [
        0, {A=>1}, \$ell[2], [5..9], ...
     ],
     Hash_array => { # variable HASH-ARRAY
        0 => ['00','01','02','03','04',], # row 0
        ...
     },
     Hash_mixed => {
        A=>\$v, B=>2, C=>3, D=>4, E=>5,
        '@' => ['C','B','D','A','E'],
        ...
     },
};
3. three-level:

ARRAY.ARRAY.ARRAY, ARRAY.HASH.ARRAY, and their combinations, e.g.

my $info = {
     Array_array_array => [
        [
          [1..9],
        ],
        [
          undef,
          [10..13],
          ...
        ],
        ...
    ],
    Array_hash_array => [
        {
          B=>[2,6..8],
          ...
        },
        ...
    ],
};
4. the combinations of the above 1..3

File and directory names and paths to them must not contain space characters.

In the names of %%%V: and %%%VAR: tags (keys and indexes), it is possible (preferably) to use only [a-zA-Z0-9_] symbols, since other symbols are currently or will be reserved in the future.

Currently, symbols: *, %, @, :, =, and / have a special purpose.

This module have reason only with perl 5.10 and higher.

ABSTRACT

Replicase in the form of the main subroutine "replication()" is minimalistic (ascetic) interpreter (uses only 3-4 basic control tags, like the system of 4 bases (nucleotides) and 3 codons, it is an optimal balance between diversity and stability) that can be used to process (fill) real TeX-LaTeX files that act as templates.

DESCRIPTION

This module is a Perl 5 extension implementing Replicase subroutines which processes TeX-LaTeX files, interpreting and executing built-in control directives (tags) of replication().

Additional subroutines ("tex_escape()", "REase()", "AGLkit()", "font_metrics()", "onecell()") serve an auxiliary role, making it possible to prepare data for populating TeX templates.

Replicase can: define and substitute variable values, execute conditional actions and capture the resulting output into a new document. Replicase was originally designed for creating programmatically configurable TeX-LaTeX documents.

Unlike other template engines, here conditionals (logic) and loops are completely separated from TeX-LaTeX document (they are hidden in the properties of the variable designated key or index for %%%V: and %%%VAR: tags) and are moved to your Perl program using this module. It's well suited for this and similar tasks, allowing you to dynamically create PDF or PostScript documents that are consistent with each other, yet easily customisable.

Replicase is a standalones, safe as a TeX-LaTeX, and fast template engine with remarkable features. All markup is based on following basic "three pillars" (directives, tags):

  • %%%V: variable_name is a short form of a regular (SCALAR) variable_name which replaces the text located to the left of it, in the line where it is located, e.g.

    Before blah, blah, \ldots blah. %%%V: myParam

    will be replaced by contents of myParam variable. However, if there is text after this variable (separated by at least one space character, which is "eaten" and will not be in the output stream), it will be added to the right of its value:

    Before blah, blah, \ldots blah. %%%V: myParam   After blah, \ldots blah.

    here ' After blah, \ldots blah.' will remain to the right of myParam value in the line.

    This construct can be used as an ON or OFF switch, for example by setting myParam to "~" (i.e. " ") or "%" the text ' After blah, \ldots blah.' will be present or absent in the finished (e.g. compiled by pdflatex, latex or tex) PDF or DVI document.

    Another trick is to use the magic value "\x{001}" (or chr(0x01)) at the beginning of a variable that acts as a trigger, i.e., output the value to the left of %%%V: in the template to the finished document. Such a trigger can work like this:

    Default value %%%V: myParam

    If myParam => "some text" then this template (pattern) will produce a TeX snippet like this:

    some text

    If myParam => "\x{001}" (or "\x{001}some text"), the result will be as folllow:

    Default value

    This trick can also be performed in a more complex way - without using a magic "\x{001}", but using the %%%ADD: tag and an additional variable (e.g. phantom), the value of which should be adjusted to the value of myParam inside area:

    %%%VAR: area
    ...
    Default value %%%ADD:%
    %%%V: phantom%
    %%%V: myParam
    ...
    %%%END:

    which, you must admit, is extremely inconvenient :(

    It is very important to understand that there are four (4) states for %%%V: variable (or %%%VAR) when the def option is enabled:

    1st.

    complete absence, i.e. variable does not exist;

    2nd.

    presence (exists) with an undefined value;

    3th.

    exists and defined value and empty (i.e. value = '', length of value == 0);

    4th state.

    defined value and not empty.

    BTW: if def option is disabled, then state (2) is identical to state (3).

    These states influence the final outcome. The following example demonstrate this.

    YES %%%V: param  NO

    (1) unless exists param, then output as is 'YES %%%V: param NO', i.e. YES.

    (2) if param == undef, then output '', i.e. empty (and text is NOT saved in %%%ADD[E]: tags, if specified).

    (3) if param eq '', then output '', i.e. empty also (but text is saved in %%%ADD[E]: tags, if specified).

    (4) if param eq ' ' then, output ' NO', i.e. it is actually 'NO' (with text is saved in %%%ADD[E]: tags, if specified).

    (4) if param eq 'there will be ' then, output 'there will be NO' (with text is saved in %%%ADD[E]: tags, if specified).

    (4) if param eq '%', then output '% NO', i.e. commented out 'NO' and it is actually empty (with text is saved in %%%ADD[E]: tags, if specified).

    (4) if param eq "\x{001}", then output YES (with text is saved in %%%ADD[E]: tags, if specified).

    There are two more magic values of %%%V: (or %%%VAR:) tag for forced completion (ending) of a finished TeX document:

    1. starting "\x{003}" (or chr(0x03)) - inserts \endinput command into TeX document and cuts off the rest of the template. Starting "\x{003}\x{003}" (or chr(0x03)chr(0x03)) - inserts \bye command into TeX document and cuts off the rest of the template.

    2. starting "\x{004}" (or chr(0x04)) - inserts \end{document} command into TeX document and cuts off the rest of the template.

    Let me repeat: the difference between "\x{003}" ("\x{004}") and directly inserting \endinput (\end{document} ) command is that remaining part of the template is cut off.

    These magical values can be set separately (singly) or together with the first "\x{001}" such as "\x{001}\x{003}" and "\x{001}\x{004}".

    Additionally, if a variable_name starts with * (i.e. *variable_name), then only the existence of that variable and its definition are checked. These conditions will confirm the insertion of the BEFORE (left) and AFTER (right, if any) values from the template, as well as the values of the surrounding %%%ADD: and %%%ADDE: tags.

    In effect, this trick helps to extend the action of a variable (and its state) beyond the immediate vicinity of %%%ADD: and %%%ADDE: tags, e.g.:

    \begin{tabular}{ccc}
    %%%VAR: area
    \mbox{ %%%ADD:%
    1 Mandatory component %%%V: *leader  ...continuation...
    } & %%%ADDE:
    2 Blah of slave %%%V: slave
    & %%%ADD:
    3 Blah of leader %%%V: leader
    \\ %%%ADDE:
    ...
    %%%END:
    \end{tabular}

    Thus, the new property (*) at the beginning of variable names (keys) confirms the existence of the variable but does not substitute its value into the template.

    Besides, if a variable_name ends in % (i.e. variable_name%), a newline is suppressed. By default, a newline always occurs after value substitution and 'After blah, \ldots blah.' if it exists.

    Also in variable_name you can use the special character "/", which denotes the "path" to the variable(s) in the passed dataset ($info) structure, e.g. %%%V: key/myParam, %%%V: key/index/myParam, etc.

    If this "path" to variable_name begins with "/", then it is absolute and the variable is searched for from the root (initial) $info structure. Otherwise, the "path" is determined relative to the current global environment, previously established in the same way.

    For example, using this trick, %%%V:/key/subkey, you can move (shift) the global environment of all subsequent (further down) %%%V: and %%%VAR: variables into the $info->{key}{subkey} area (scope). To return to the root (initial) $info global environment of all variables, call %%%V: /.

    If this "path" ends with a regular (scalar) variable or a reference to one, then the global environment is not redefined, e.g. %%%V: key/index/myParam, here key/index "path" is exclusively the local environment of myParam variable, the value of which is inserted into the template.

    %%%V: nested within the scope of %%%VAR: tag do not change the global environment, and the "/" character is not a separator in the "path". It is a normal character in the variable_name.

    CONCLUSION: standalone %%%V: tag (outside %%%VAR: scope) can be used to set the global variable lookup environment.

    %%%V: can be nested in an ARRAY or HASH %%%VAR: tag, but in SCALAR (or REF.SCALAR) %%%VAR: it will not work and will be discarded.

    There's a special variable_name = @, which means to "use all elements of an ARRAY". Therefore, this only makes sense for ARRAY variables or HASH that have @ key (see example above).

    Using @ for HASH variables is also acceptable. In this case, it is assumed that a key with this name exists in the hash, which stores a list (vector) of the keys of this hash in the order they are inserted into TeX template.

  • %%%VAR: variable_name is start of full form of regular (SCALAR, REF.SCALAR) or complex (HASH, ARRAY) variable_name, keeping the template text in the line preceding up to %%%VAR: but completely replacing everything up to first %%%END: (%%%ENDT:, %%%ENDZ:, or a new %%%VAR:, or %%%TDZ:) tag inclusive.

    External Blah, blah, \ldots blah:  %%%VAR: myParam
    Internal Blah, blah, \ldots
    \ldots
    Internal Blah, \ldots %%%END:

    or a template like this with additional internal %%%ADD: and %%%ADDE: tags:

    %%%VAR: myParam
    \mbox{ %%%ADD:%
    \rule{0mm}{4.5em} %%%ADD:
    head \ldots %%%ADD:
    ... SPECIFY VALUE of myParam!
    tail \ldots %%%ADDE:%
    } %%%ADDE:
    %%%END:

    If myParam = 1234567890 (it's SCALAR), then that template will lead to the creation of such a TeX fragment:

    External Blah, blah, \ldots blah: 1234567890

    or respectively:

    \mbox{\rule{0mm}{4.5em}
    head \ldots
    1234567890
    tail \ldots}

    BTW: if myParam = undef (i.e. undefined) and facultative option (see below) def is set (e.g. 1), then these fragments will be missing from the finished TeX.

    Usually HASH and ARRAY variable_name are used in the template to create (fill) tables or table-like boxes.

    %%%VAR: tag is similar to %%%V: tag, where the variable name can be used to specify its search "path" using a special symbol, "/". However, this "path" does not affect the global environment. It only sets the local environment within the scope of %%%VAR: tag.

    Nested %%%VAR: tags will not work and are treated as %%%END: tags, i.e. tags for early termination of the scope.

    It is very important to understand that there are four (4) states for %%%VAR: variable (just as for %%%V, but with a nuance of 1st state) when the def option is enabled:

    1st.

    complete absence, i.e. variable does not exist;

    2nd.

    presence (exists) with an undefined value;

    3th.

    exists and defined value and empty (i.e. value = '', length of value == 0);

    4th state.

    defined value and not empty.

    BTW: If def option is disabled, then state (2) is identical to state (3).

    These states affect the final result %%%V: of %%%VAR: similarly to simple (SCALAR and REF.SCALAR variable) %%%V: or %%%VAR: (see above), but there is a slight difference for the 1st state when a non-existent (complete absence) key/name is specified. In this case, everything on the line along with %%%V: is discarded (it will not appear in the final document), while any surrounding context defined by %%%ADD: and %%%ADDE: is passed on to the next existing key/name belonging to %%%VAR:.

  • There are three options for %%%ENDx tags:

    1. %%%END: is used to specify the end of %%%VAR: tag.

    BTW: if this tag is omitted and there are no further %%%ENDT:, %%%ENDZ:, %%%VAR:, and %%%TDZ: tags, all text to the end of document will be replaced by variable_name specified in %%%VAR: tag.

    2. %%%ENDZ: is used to mark the end of the %%%TDZ: tag.

    %%%TDZ: marks The Dead Zone in the template free from any tag searches. It can also be used to disable (deactivate) tags.

    3. %%%ENDT: is used to mark the end of a template.

    It is typically applied to the bottom of a document to terminate tag searches and speed up processing. It can also be used to disable (deactivate) tags.

    ATTENTION! Text (and newline) located in line with any %%%END:, %%%ENDZ:, and %%%ENDT: tags will be discarded.

  • %%%TDZ: marks the start of The Dead Zone in the template free from any tag searches. This tag must start at the very beginning of the line and be single on the line.

    It can also be used to disable other tags.

The following tags can be located within the block limited by ARRAY and HASH of %%%VAR: and any %%%ENDx, %%%TDZ:, or a new %%%VAR: tags:

  • %%%V: key|index with setting of key (in case of HASH %%%VAR:, i.e. %%%V: keyA, %%%V:keyB, etc.) or index (in case ARRAY %%%VAR:, i.e. %%%V:0, %%%V:1, %%%V:2, %%%V:-7, etc.). Here keys or indexes are columns (or positions) of the table (filled area) being created.

    index can also be specified as a comma-separated list of numbers (array indices, e.g., 1, -7, 3, 5, -9), or as a closed (0-7, 4-10), left-open (-3-), or right-open (0-) range of array indices. In this case, spaces are also not allowed.

    Negative values and left-open range indicate the reverse order of the array indices, i.e., counting from the end. For example, -1- means from -1,-2,-3,... to the initial element of the array (vector).

    There's @ - a special name of index which means "to use all elements of an ARRAY". It's actually short for right-open range: 0-. Therefore, this only makes sense for ARRAY variables.

    Using @ for HASH variables is also acceptable. In this case, it is assumed that a key with this name exists in the hash, which stores a list (vector) of the keys of this hash in the order they are inserted into TeX template.

    If a key|index ends in % (e.g. keyA%, %%%V:0%, %%%V:@%, etc. ), a newline is suppressed. By default, a newline always occurs after value substitution and additional text to the right of %%%V: if it exists.

  • There are four (4) options for %%%ADDx tags:

    1. %%%ADD: adds text before variable specified in %%%V: tag.

    The added text is taken from the beginning of the line to the beginning of %%%ADD: (i.e. text located on the left), e.g.

    Head blah, blah, \ldots blah. %%%ADD: Tail blah, blah, \ldots

    this text will be added: 'Head blah, blah, \ldots blah.', and the text located to the right of %%%ADD: (i.e. Tail blah, blah, \ldots in this case) will be discarded.

    Or, if %%%ADD: is located at the very beginning of line, then after it to the end of line (i.e. text located on the right), e.g.

    %%%ADD: Tail blah, blah, \ldots

    this text will be added: 'Tail blah, blah, \ldots'.

    If the following %%%V: tag is not present, then the text is output at the end of all keys or indexes (columns) each table (filled area) row.

    %%%ADD: can also be used for SCALAR and REF.SCALAR variable, but without %%%V: tag because it is redundant and not supported:

    %%%VAR: myParam
    \mbox{ %%%ADD:%
    \rule{0mm}{4.5em} %%%ADD:
    head \ldots %%%ADD:
    ... SPECIFY VALUE of myParam!
    tail \ldots %%%ADDE:%
    } %%%ADDE:
    %%%END:

    If myParam = 1234567890 (it's SCALAR), then that template will lead to the creation of such a TeX fragment:

    \mbox{\rule{0mm}{4.5em}
    head \ldots
    1234567890
    tail \ldots}

    i.e. the SCALAR value will be located after %%%ADD: tags and before %%%ADDE: tags, in other words, between them, if they exist.

    BTW: By combining auxiliary parameters and the def facultative option (see below), which specifies discarding (ignoring) undefined values and their associated %%%ADD: structures, you can create a logic scheme for disabling %%%ADD: tags. For example:

    %%%VAR: myTable
    \\  %%%ADD:
    % %%%V: head
    
    etc...
    
    \\  %%%ADD:
    \midrule  %%%ADD:
    %  %%%V: rule
    
    my $info = {
         myTable => [
          {head =>'%', ... }, # 'rule' is undefined
          {rule =>'%', ... }, # 'head' is undefined
          ...
         ]
         ...
      };
    
     my $msg = replication( $file, $info, def =>1 );
    2. %%%ADDE: is similar to %%%ADD:.

    Means Ending %%%ADD, but it differs in that text is added after variable specified in %%%V: tag.

    This %%%ADDE: tag must follow immediately after %%%V: tag (i.e. there should not be %%%ADD: tag before it), otherwise it will also become a regular %%%ADD: tag, for example for the next %%%V:.

    %%%ADDE: can also be used for SCALAR and REF.SCALAR variable, but without %%%V: tag because it is redundant and not supported. Here you must correctly place %%%ADD: and %%%ADDE: tags yourself: %%%ADD: denotes what will come before the variable value, and %%%ADDE: - after it (see above).

    3. %%%ADDX: is similar to %%%ADD:.

    For all lines (records) eXcept for the outermost elements: column (0) of first record (0) or after the last column of last record.

    4. %%%ADDA: is similar to %%%ADD:.

    Means that %%%ADD is Always present, but it is not linked to any %%%V: in the block of %%%VAR:, meaning its contents will not depend on the variable's uncertainty of %%%V:, and its value will be output in any case and in the appropriate order.

    %%%VAR: myHash
    \mbox{ %%%ADDA:%
    \rule{0mm}{4.5em} %%%ADDA:%
    head \ldots %%%ADD:
    ... SPECIFY VALUE of myKey! %%%V: myKey
    tail \ldots %%%ADDE:%
    } %%%ADDA:
    ...
    %%%END:

    If myHash = { myKey => undef, ... }, then that template will lead to the creation of such a TeX fragment:

    \mbox{\rule{0mm}{4.5em}}

    If any %%%ADDx: tag ends in % (e.g. %%%ADD:%, %%%ADDA:%, %%%ADDE:%, or %%%ADDX:% ), a newline is suppressed. (By default, a newline always occurs after adding text).

Only ONE tag can be located on ONE line of input template.

Tag names must be in %%%UPPERCASE:.

Tags can "absorb" ONE whitespace character around them (left and/or right), if present.

SUBROUTINES

LaTeX::Replicase provides these subroutines:

replication( $source, $info [, %hash_options ] );
tex_escape( $value [, $options ] );
REase( $value [, $options ] );
AGLkit( [ $options ] );
font_metrics( $AFMfile [, $options ] );
onecell( $string, $options );

replication()

my $msg = replication( $source, $info [, %hash_options ] )

Creates a new output file from the specified TeX-document $source, which is a template. The TeX-template $source can be either a TeX-file or an array reference, each element of which is a TeX-string (with line break \n if necessary).

File name of $source can be absolute, i.e. with a full path (include directories and subdirectories). File and directory names and paths to them must not contain space characters. It is also recommended to use only ASCII characters in the file name.

The output file name is extracted from $source. Under no circumstances will $source be overwritten by the new one.

If $source is an array reference and no target file name is specified by ofile option, then ready.tex file will be created in a random subdirectory (its name is stored in $$ variable) of current directory.

$info HASH or ARRAY is used to fill template:

$info = { };
# or
$info = [ ];

When replication processes $source it identifies tags and replaces them with the result of whatever the tag represents (e.g. variable value for %%%V: or from %%%VAR: to %%%END:). Anything outside the tag(s), including newline characters, are left intact.

After replication completes, the input $info of remains unchanged, i.e. all internal modifications do not affect the original values.

The following %hash_options can be used when calling replication:

outdir
my $msg = replication( $source, $info, outdir => $target_dir );

A new $source will be created in $target_dir directory. File and directory names and paths to them must not contain space characters.

ofile
my $msg = replication( $source, $info, ofile => $ofile );

A new $ofile will be created. ofile option suppresses (eliminates) outdir option, i.e. file name of $ofile can be absolute. File and directory names and paths to them must not contain space characters.

If the completed template (ready TeX) needs to be output directly to the console (or, for example, for the Web), you can specify:

ofile => *STDOUT

Of course, in this case outdir option will not be valid either.

utf8

This option forces specifies the template and output files' character encoding as utf8:

my $msg = replication( $source, $info, utf8 =>1 );
esc

This option applies tex_escape() subroutine to all incoming values to mask 9 active TeX characters & % $ # _ { } ^ \ (see description of "tex_escape()" subroutine below).

For example, the simplest way to use esc is:

replication( $source, $info, esc =>1 );
replication( $source, $info, esc =>'~');

BTW: If a number >1 is specified in this option (e.g. esc => 2), then it cannot be overridden (replaced) from the template via %%%V:=esc= 0|1|2|~|... tag.

In general, the esc option can contain the following keys:

replication( $source, $info, esc =>'~ hyphen !stag -stag +stag;REase, strong mutual');

i.e. in esc these keys can be separated by spaces, '_', and word boundaries. For a description of these keys, see the sections on "tex_escape()" and "REase()".

This option can also be changed dynamically in the template itself using global %%%V:=esc= 0|1|~|... tag, but can be changed only if when calling replication() for esc option the priority is not specified >1, e.g. esc => 2....

tile

This option specifies the size (in characters) of the maximum uncut non-alphabetic sections in the range from 1 to tile + 1, e.g.

$msg = replication( $source, $info, esc => 'REase', tile => 2 );

By default, tile = 3. tile option has meaning if replication() is called with REase in esc or _ACTIONS_ option.

Valid values for tile are from 2 to 9. For a description of tile, see the section on "REase()".

_ACTIONS_

This option is an array of names (scalars), references, and hashes to internal (tex_escape, REase) and external user-defined subroutines that will be run in the order specified by this array (like a pipeline) during the actual template filling with the %%%V: variable_name (or %%%VAR:) value from $info. For example:

my $actions = [
     \&mySub_1st,
     'tex_escape',
     'REase',
     {
       _name_ => 'mySub_2nd', # optional sub name
       _code_ => sub{
         # $_[0] is $value of variable_name
         # $_[1] is $hash_options of replication(), e.g. $_[1]->{_MFLAGS_}
         #
         # ... we do something with $_[0] ...
         #
         my $mflag = 0b00... ; # set the value modification bit flag (see below)
         return $mflag;
       }
     },
     {
       _code_ => \&mySub_3th,
     },
 ];

$msg = replication( $source, $info, _ACTIONS_ => $actions );

For example, the following replication() calls will be executed completely equivalently:

$msg = replication( $source, $info, esc => 'REase');
$msg = replication( $source, $info, _ACTIONS_ => ['tex_escape', 'REase', ] );
$msg = replication( $source, $info, esc => 'REase', _ACTIONS_ => ['REase', ]);
$msg = replication( $source, $info, esc => 'REase', _ACTIONS_ => ['tex_escape', ]);
$msg = replication( $source, $info, esc => 'REase', _ACTIONS_ => ['tex_escape', 'REase', ]);

but this option will differ from them in the order of calling subroutines:

$msg = replication( $source, $info, _ACTIONS_ => ['REase', 'tex_escape', ] );

first REase() will be executed, then tex_escape().

Thus, _ACTIONS_ helps to finely control the template filling process. Duplicate or erroneous subroutines will be discarded.

If a custom user subroutine is used in _ACTIONS_ pipeline, it is important to return $mflag value, which then goes into the _MFLAGS_ option and is needed for tex_escape() and REase() if they are called later in the pipeline. These subroutines will not be executed if _MFLAGS_ & 0b0100. tex_escape() will also not work if _MFLAGS_ & 0b0110.

def

This option specifies discarding (ignoring) undefined values and associated structures (%%%ADD...), i.e. dictates that only defined values be into account.

my $msg = replication( $source, $info, def =>1 );

This option is useful, for example, to remove blocks of text and for creating merged cells in tables (using \multicolumn LaTeX-command) and applies to all incoming data. Also this option can be used as an ON or OFF switch (see above).

If def option is not specified or is 0, then all undefined values are replaced with an empty value, i.e. '' (length is 0).

This option can also be changed dynamically in the template itself using global %%%V:=def= 0|1 tag, but can be changed only if when calling replication() for def option the priority is not specified >1, e.g. def => 2.

ignore

This option specifies silently ignore undefined name|key|index of %%%V: and %%%VAR: tags:

my $msg = replication( $source, $info, ignore =>1 );

This option can also be changed dynamically in the template itself using global %%%V:=ignore= 0|1 tag. but can be changed only if when calling replication() for ignore option the priority is not specified >1, e.g. ignore => 2.

silent

This option activates silent mode of operation:

my $msg = replication( $source, $info, silent =>1 );

This option can also be changed dynamically in the template itself using global %%%V:=silent= 0|1 tag. but can be changed only if when calling replication() for silent option the priority is not specified >1, e.g. silent => 2.

debug

This option sets local debug mode:

my $msg = replication( $source, $info, debug =>1 );
if( ! $msg ) {
  say 'Ok';
}
else {
  say for @$msg;
}

This option can also be changed dynamically in the template itself using global %%%V:=debug= 0|1 tag. but can be changed only if when calling replication() for debug option the priority is not specified >1, e.g. debug => 2.

Another way is to set the $DEBUG package variable to enable debugging messages (global debug mode).

$LaTeX::Replicase::DEBUG = 1;

replication returns undef or a reference to an error (and/or debug) message(s) array.

tex_escape()

my $mflag = tex_escape( $value [, $options ] );

Masks (or replaces with equivalents) the active 9 TeX characters: &, %, $, #, _, {, }, ^, \ with the corresponding: \&, \%, \$, \#, \_, \{, \}, \^\/, \char92\/ in the input $value

With the facultative (optional) option ~, you can additionally replace the character ~ with the corresponding \~\/, e.g.:

tex_escape( $value, '~');

$options is optional and can be specified as a SCALAR or a HASH. For example, $options is a HASH:

my $mflag = tex_escape( $value, {
                esc => '~ hyphen; !stag -stag, +stag REase, strong,mutual',
                tile => 4,
                _MFLAGS_ => 0b0001,
              }
            );

For example, $options is a SCALAR:

my $mflag = tex_escape( $value, '~hyphen, REase !stag -stag +stag; strong mutual');

i.e. the SCALAR form of $options allows passing additional options only as esc. Key separators in esc option can be spaces, '_', and word boundaries.

hyphen

This option makes compound words with "active" hyphens, i.e. makes a replacement ...abc-def... with ...abc"=def....

REase

includes an internal call to "REase()" subroutine. (See below).

start tag %%%:

If the $value starts with the %%%: tag, then this tag is removed (e.g. $value = '%%%:$\frac{12345}{67890}$' is converted to $value = '$\frac{12345}{67890}$'), and the value itself is not masked, it is skipped without changes. By default (without additional -stag option), only ONE 1st start tag %%%: is removed. This means that the following start tags (stag) will remain untouched if they are set.

Three options (!stag, -stag, and +stag) affect the action of the start tag (%%%:):

!stag

This option means to ignore the start tag and skip it as if it does not exist, and masking of active symbols.

-stag

This option means to remove all start tags, and masking of active symbols

+stag

This option means to keep the 1st start tag.

undef

Their (stags) absence means deleting the 1st start tag (%%%:) and exiting tex_escape() without masking active symbols.

All three options, or just some of them, may be present at the same time, but !stag suppresses the others.

Re-masking active symbols

By default, if already masked active symbols (\& \% \$ \# \_ \{ \} \^ \char92), they are skipped.

Also classic TeX-LaTeX-commands: \textbackslash \relax \hskip \<tab> \- \* \/ \= \. \~ \' \` \" \, \; \! \> are skipped in this case.

This means that when tex_escape() re-processes a previously processed $value, no additional escaping of these command symbols will occur. However, other TeX objects will be affected, if they exist.

Two additional options -- strong and mutual influence this behavior.

strong

ignores all previously masked characters listed above, except for the TeX-LaTeX-commands: \char92, \textbackslash, \relax, and \hskip.

mutual

does not pay attention to the smaller number of characters and TeX-LaTeX-commands: \& \% \$ \# \_ \{ \} \^ \<tab> \- \* \/ \= \. \~ \' \` \" \char92 \textbackslash \relax \hskip

return codes

tex_escape() returns a bit flag $mflag indicating whether $value is modified:

0b0000

there were no changes (modifications).

0b0001

there were changes and they affected only non-TeX structures.

0b0010

changes were made and affected TeX structures and/or the start tag.

tex_escape() will not be executed if input _MFLAGS_ & 0b0110.

REase()

my $mflag = REase( $value [, $options ] );

"Cuts" ("splits") $value, recognizing non-alphabetic sections in it (except for these characters: ., >, <, }, {, ', `, ", =, _, -, and finally \ character, a sequence of characters that TeX cannot break with ordinary word breaks) and glues the "cut" sections together with stretchable "glue" (i.e., a "spring" --- {\hskip0pt plus .02em}).

For example, this gibberish:

my $value = '~$&,%,$,#,_,{,},^,\2qw\ea-sdf-124-590\\\\\\>>>>---1';
my $mflag = REase( $value );

converts to a sequence (by default, tile = 3)

'{\hskip0pt plus .02em}~$&,'.
'{\hskip0pt plus .02em}%'.
'{\hskip0pt plus .02em},$,#'.
'{\hskip0pt plus .02em},'.
'{\hskip0pt plus .02em}_,{'.
'{\hskip0pt plus .02em},'.
'{\hskip0pt plus .02em}},^'.
'{\hskip0pt plus .02em},'.
'{\hskip0pt plus .02em}\2'.
'{\hskip0pt plus .02em}qw\ea'.
'{\hskip0pt plus .02em}-'.
'{\hskip0pt plus .02em}sdf'.
'{\hskip0pt plus .02em}-'.
'{\hskip0pt plus .02em}1'.
'{\hskip0pt plus .02em}24'.
'{\hskip0pt plus .02em}-'.
'{\hskip0pt plus .02em}5'.
'{\hskip0pt plus .02em}9'.
'{\hskip0pt plus .02em}0\\\\\\>>'.
'{\hskip0pt plus .02em}>>'.
'{\hskip0pt plus .02em}---'.
'{\hskip0pt plus .02em}1'

This will allow TeX, when creating (layout) the finished document, to break such sequences into separate small fragments and lines and place them in very narrow TeX blocks, such as narrow table cells, without "manual adjustment" (intervention by Homo sapiens).

$options is optional and can be specified as a SCALAR or a HASH. For example, $options is a HASH:

my $mflag = REase( $value, { tile => 2, esc => '!stag -stag', _MFLAGS_ => 0 } );

For example, $options is a SCALAR:

my $mflag = REase( $value, '!stag -stag');

i.e. the SCALAR form of $options allows passing additional options only as esc.

tile

Here, the main auxiliary option is tile, which specifies the size (in characters) of the maximum uncut non-alphabetic sections in the range from 1 to tile + 1. For example, for tile = 5, the sizes of uncut non-alphabetic sections will be from 1 to 6 characters, e.g.:

$mflag = REase( $value, { tile => 5 } );

Valid values for tile are from 2 to 9.

If the $value ends with TeX-command \relax\/, then the value itself is not modified, it is skipped. \relax\/ remains untouched at the end.

REase() also depends on %%%: start tag and the !stag, -stag options (but not the +stag option), similar to tex_escape().

return codes

REase() returns a bit flag $mflag indicating whether $value is modified:

0b0000

there were no changes (modifications).

0b0001

there were changes and they affected only non-TeX structures.

0b0010

changes were made and affected TeX structures and/or the start tag.

0b0100

changes were made and greatly affected TeX structures.

REase() will not be executed if _MFLAGS_ & 0b0100.

AGLkit()

my $agl = AGLkit( [ $options ] );

Returns a hash table that maps glyph names to a numeric character Unicode (in decimal (default) or hexadecimal format) or the corresponding character equivalents for the glyphs defined by Adobe in what is known as the 'Adobe Glyph List' (AGL), contained in the well-known 'glyphlist.txt' file. (see https://github.com/adobe-type-tools/agl-aglfn/blob/master/glyphlist.txt)

By default (i.e., without any additional options), a hash is returned using the ISO-8859-1 character set (also known as ISO-Adobe), supplemented by the 'Adobe Standard Cyrillic Glyph Names' character set, with character codes represented in decimal format. (see https://en.wikipedia.org/wiki/Adobe_Glyph_List and https://adobe-type-tools.github.io/font-tech-notes/pdfs/5013.Cyrillic_Font_Spec.pdf). For example:

my $agl = AGLkit();
say Dumper $agl;

Output a hash of 325 glyphs:

$VAR1 = {
        'Atilde' => 195,
        'D' => 68,
        'afii10100' => 1107,
        'acute' => 180,
...
        'sterling' => 163,
        'Ucircumflex' => 219,
        'H' => 72,
        'R' => 82,
        'V' => 86
      };

This subroutine accepts a list of optional settings in the form of a hash $options. For example:

my $options = { 
  glyphlist => 'glyphlist.txt', # glyph list file
  mate => 'symbol', # of Unicode | 'hex' Unicode number (native). By default, decimal Unicode number
};

$agl = AGLkit( $options );

Output:

$VAR1 = {
        'ringhalfrightbelowcmb' => "\x{339}",
        'afii10831' => "\x{f6c7}",
        'thorn' => 'þ',
        'brokenbar' => '¦',
        'E' => 'E',
        'two' => '2',
        'exclam' => '!',
        'twosuperior' => '²',
...
      };

glyphlist

This option allows you to transfer a file containing glyphs and their corresponding Unicode character codes, similar the well-known 'glyphlist.txt' file. (see https://github.com/adobe-type-tools/agl-aglfn/blob/master/glyphlist.txt). E.g., in Debian (with the TeX Live system installed), the file you are looking for is located at the path /usr/share/texlive/texmf-dist/fonts/map/glyphlist/

And the most reliable way to find a file is to use the kpsewhich command in the terminal:

$ kpsewhich glyphlist.txt

mate

This option allows you to specify which mapping to set for glyphs: Unicode 'symbol' or 'hex' Unicode number. By default, decimal Unicode number (for undefined mate). For example:

$agl = AGLkit( {mate =>'hex',} );

Output:

$VAR1 = {
        'exclam' => '21',
        'twosuperior' => 'B2',
        'brokenbar' => 'A6',
        'E' => '45',
        'two' => '32',
        'thorn' => 'FE',
        'afii10831' => '439',
...
      };

Invalid glyph names and names beginning with a dot ('.'), are discarded.

font_metrics()

my $font_metrics = font_metrics( $AFMfile [, $options ] );

This subroutine allows you to obtain information about a font and the metrics of various glyphs within that font from an AFM (Adobe Font Metrics) file --- $AFMfile. All measurements in AFM files are expressed in units equal to 1/1000 of the font's scale factor.

This subroutine accepts a list of optional settings in the form of a hash $options. For example:

my $font_metrics = font_metrics('PTC55F.afm'); # to get the metrics of 'PT Sans Caption' font
# or
$font_metrics = font_metrics('PTC55F.afm', { glyphlist =>'glyphlist.txt',} );

say Dumper $font_metrics;

Returns a hash containing three hashes: 'WX' -- character widths, 'Bbox' -- Bounding box information, and 'KPX' -- kerning pairs ash contains the kerning values for adjacent characters:

$VAR1 = {
        'WX' => {
                  '118' => '535',
                  '1060' => '857',
...
                  '177' => '554',
                },
        'Bbox' => {
                    '118' => '0 -11 535 525 ',
                    '1060' => '43 -20 813 720 ',
...
                    '177' => '43 168 511 699 ',
                  },
        'KPX' => {
                   '118' => {
                              '32' => '-36',
                              '382' => '-10',
...
                              '118' => '7',
                              '44' => '-72'
                            },
...
                   '1060' => {
                               '62669' => '-16',
                               '1199' => '-16',
...
                               '8218' => '-31'
                             },
                 }
      };

glyphlist

This option is similar to the one in "AGLkit()" subroutine (see above).

mate

This option is similar to the one in "AGLkit()" subroutine (see above), i.e. the allowed values are 'symbol', 'hex', and an additional 'glyph' of Adobe. By default, decimal Unicode number (undefined mate).

noBbox, noKPX

These options mean not to generate 'Bbox' and 'KPX' hashes respectively.

onecell()

my( $cell ) = onecell( $string, $options );

This method places (lays out) a given plain-text $string (i.e., a paragraph, with no TeX/LaTeX commands! and no \n characters) into a cell (or box) of a specified width, returning an array of lines or the number of lines occupied within the cell.

These lines, including their word breaks (in the form of TeX command '\-'), will largely correspond to their actual layout in a PDF document generated from them --- for instance, when using a LaTeX table environment (such as 'tabular' or 'longtable') processed with the 'pdflatex' command.

The formation of these lines (or more precisely, the hyphenation of words at the end of lines) is influenced by the 'hyphenation' parameter, which results in two ways of arranging lines within a cell: "compact" (A) and "natural" (B).

(A)

If 'hyphenation' is missing or 'action' for hyphenating words of the language of the given text ($string) are not specified, then a case of the most compact packing of lines into a cell/box is formed, with the minimum possible number of hyphenations in words. In PDF output, this is achieved by setting the '\looseness' parameter for a paragraph within a cell/box to -3 or lower (e.g., \looseness=-4, etc.).

(B)

If 'action' (from modules such as Text::Hyphen, Text::Hyphen::RU, TeX::Hyphen, etc. with hyphenate() method), are specified in the 'hyphenation' parameter to handle word hyphenation for the languages present in the given text, the result will include natural, language-appropriate word breaks. In this scenario, the number of hyphenated words is kept to a reasonable minimum; however, unlike in case (A), the total number of lines within a cell/box may increase by one or two. This depends on the width of the cell/box: the narrower (smaller) the width (e.g. option cell_width < 10mm), the more likely it is that the number of lines will exceed that of case (A).

If the strings obtained in case (B) are not used for PDF creation (via the 'pdflatex' command) --- and the original text $string is used instead -- then the results from (B) will match the PDF output (in terms of word hyphenation and the number of lines within a cell) only if the text language is correctly specified -- either for the entire document (in the preamble) or specifically for that cell (for instance, by using the 'otherlanguage' environment or commands such as '\foreignlanguage{}{}' and '\selectlanguage{}') --- and provided that the hyphenation patterns used in both cases are identical.

The following options are mandatory:

cell_width

Width of cell/box (pt).

font_metrics

Hash (table) of font metrics with 'WX' (pairs of decimal Unicode number to horizontal (X) width of a character), and optional 'KPX' -- Kern Pair X. This table can be obtained using "font_metricst()" subroutine with default parameters (see above).

The following parameters are optional:

base_font_size

Depending on the document's base font size (pt), e.g. 12pt (see \documentclass[...pt]). By default, this value is 10 (i.e. 10pt).

font_size

TeX-font size of text in cell/box: 'tiny', 'scriptsize', 'footnotesize', 'small', 'normalsize', 'large', 'Large', 'LARGE', 'huge', and 'Huge'. By default, this value is 'normalsize'.

space

Regular space between words (pt) -- fontdimen 2. In LaTeX, you can determine the compressibility parameters for the space between words by accessing the font parameters (see above \fontdimen 2)

You can output the current interword space parameters to the compilation log or directly onto the page using the \the\fontdimen command:

\documentclass{article}
\begin{document}
  Regular whitespace (fontdimen 2): \the\fontdimen 2 \font\\
  Whitespace stretching (fontdimen 3): \the\fontdimen 3 \font\\
  Whitespace shrink (fontdimen 4): \the\fontdimen 4 \font
\end{document}

If this parameter is not specified, the value of space from the font_metrics is used.

shrink

Space compressibility (pt) --- the extent to which a space can become narrower than its base value if the line is compressed (fontdimen 4). A standard space in LaTeX is a flexible space (glue) and consists of three components: a normal width, a stretch component, and a shrink component. In LaTeX, you can determine the compressibility parameters for the space between words by accessing the font parameters (see above \fontdimen 4).

By default, this value is 0.

merge

If merge => 1 -- return a combined string (paragraph) and its total width (length) in (*100pt), rather than an array of lines.

offset

Offset from the beginning of $str from which characters for cell are extracted. By default, this value is 0.

limit

The maximum allowable number of lines for a cell. By default, the number of lines is unlimited.

hyphenation

Array of methods which hyphenates words in specified languages, e.g.:

use Text::Hyphen;
use Text::Hyphen::RU;

my $hyp_en = new Text::Hyphen( min_word =>4);
my $hyp_ru = new Text::Hyphen::RU( min_word =>4);

my $hyphenation = [
       { name =>'en', action => $hyp_en, }, # English
     # OR
     # { msk => qr/[a-zA-Z]+/o, action => $hyp_en, },

       { name =>'ru', action => $hyp_ru, }, # Russian
     # OR
     #  { msk => qr/[а-яА-Я]+/o, action => $hyp_ru, },
    ];

The primary requirement for action used for this hyphenation option is that their interface must resemble that of Text::Hyphen module; specifically, when called in a list context, the object-oriented subroutine $hyp-hyphenate($word)> should break the $word into parts at the hyphenation points and return a list of these parts.

It is also acceptable to use a regular function rather than an object-oriented subroutine $hyp-hyphenate($word)>, provided that its interface matches the one specified above—that is, it must return a list of word fragments.

For name key, two predefined values are currently permissible: 'en' (English) and 'ru' (Russian).

To typeset non-English and non-Russian texts, pass in a Text::Hyphen-like object which responds to the hyphenate method, returning a list of hyphen positions for that particular language (native Text::Hyphen defaults to American English hyphenation rules). See Text::Hyphen for the interface.

For non-English and non-Russian languages, you need to use the msk key, in which you specify a mask for identifying the language based on a $word.

Examples #1:

use utf8;
use open ":std", ":encoding(utf8)";

use LaTeX::Replicase qw(font_metrics onecell); # :all
use Text::Hyphen;
use Text::Hyphen::RU;
use Data::Dumper;

my $mm2pt = 2.845276; # 1mm ~= 2.845276pt
my $cell_width = 30; # (mm)
$cell_width *= $mm2pt; # (mm) to (pt)

my $hyp_en = new Text::Hyphen( min_word =>4);
my $hyp_ru = new Text::Hyphen::RU( min_word =>4);

my $op = {
    cell_width => $cell_width, # width of cell/box, (pt)
    font_metrics => font_metrics('PTC55F.afm', { glyphlist => 'glyphlist.txt', noBbox =>1 }),
    base_font_size => 10, # depending on the document's base font size (pt), see \documentclass[...pt]
    # font_size => 'normalsize', # TeX-font size of text in cell/box
    space => 2.43, # Regular space between words (pt), see fontdimen 2
    shrink => 0.81, # whitespace shrink (pt), see fontdimen 4
    # merge => 1,
    # offset => 0,
    # limit => 25,
    hyphenation => [
       { name =>'en', action => $hyp_en, }, # English
     # OR
     # { msk => qr/[a-zA-Z]+/o, action => $hyp_en, },

       { name =>'ru', action => $hyp_ru, }, # Russian
     # OR
     #  { msk => qr/[а-яА-Я]+/o, action => $hyp_ru, },
    ],
};

my $string = "I was going to do something today but I haven't finished doing nothing from yesterday.
Я собирался кое-что сделать сегодня, но еще не закончил ничегонеделание со вчерашнего дня    ";
say 'size of string = ', length( $string );

my $nLines = onecell( $string, $op );
say "number of lines = $nLines";

my( $cell ) = onecell( $string, $op );
say Dumper $cell;

$op->{merge} => 1;
my( $cell ) = onecell( $string, $op );
say Dumper $cell;

OUTPUT:

size of string = 180
number of lines = 12
$VAR1 = {
        'lines' => [ # arrays of no empty lines
                     'I was going to do ',
                     'something today ',
                     'but I haven\'t fin\-',
                     'ished doing noth\-',
                     'ing from yes\-ter\-',
                     'day. Я собирался ',
                     'кое-что сделать ',
                     'сегодня, но еще ',
                     'не закончил ни\-',
                     'че\-го\-не\-де\-ла\-ние ',
                     'со вчерашнего ',
                     'дня'
                   ],
        'stop' => 176, # position in $string where the extraction of symbols into cell stopped
        'wxL' => [ # arrays of line widths (*100pt) for 'lines'
                   8106,
                   8247,
                   7530,
                   8171,
                   7243,
                   8257,
                   7901,
                   7882,
                   7490,
                   7692,
                   7423,
                   1826
                 ],
        'numL' => 12 # number of no empty lines
      };

$VAR1 = {
        'wxL' => [
                   87768
                 ],
        'lines' => [
  "I was going to do something today but I haven't fin\\-ished doing noth\\-ing from yes\\-ter\\-day. Я собирался
    кое-что сделать сегодня, но еще не закончил ни\\-че\\-го\\-не\\-де\\-ла\\-ние со вчерашнего дня"
                   ],
        'numL' => 12,
        'stop' => 176
      };

The output hash contains the position in $string where the extraction of symbols into cell stopped under 'stop' key. If all non-whitespace characters have been extracted from $string and 'limit' option is specified, then stop = -1 is returned.

LIMITATIONS: The strings in 'lines' will have no leading spaces. The last string will have no trailing spaces. Words in 'lines' will be separated by exactly ONE SPACE and may contain TeX hyphenation commands ('\-').

EXPORT

LaTeX::Replicase exports nothing by default. Each of the subroutines can be exported on demand, as in

use LaTeX::Replicase qw( replication );

and the tag all exports them all:

use LaTeX::Replicase qw( :all );

DEPENDENCIES

LaTeX::Replicase is known to run under perl 5.10.0 on Linux. The distribution uses File::Basename, File::Path, File::Compare, and Carp.

SEE ALSO

For LaTeX2e details see this unofficial reference manual: https://tug.org/texinfohtml/latex2e.html

For 'Adobe Glyph List' (ISO-8859-1 character set, also known as ISO-Adobe) see https://en.wikipedia.org/wiki/Adobe_Glyph_List, https://github.com/adobe-type-tools/agl-aglfn

For 'Adobe Standard Cyrillic Glyph Names' character set see https://adobe-type-tools.github.io/font-tech-notes/pdfs/5013.Cyrillic_Font_Spec.pdf

Perl modules that offer similar functionality:

Template::Latex, LaTeX::Easy::Templates, PostScript::DecodeGlyphName, Font::GlyphNames, Font::AFM

SUPPORT AND BUGS

You can find documentation for this module with the perldoc command:

perldoc LaTeX::Replicase

Please bug reports, comments or feature requests to: https://github.com/AlessandroGorohovski/LaTeX-Replicase

The original bug tracker can be found at: https://rt.cpan.org/Public/Dist/Display.html?Name=LaTeX-Replicase

AUTHOR

Alessandro N. Gorohovski, <an.gorohovski@gmail.com>

COPYRIGHT AND LICENSE

Copyright (C) 2010-2026 by Alessandro N. Gorohovski

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available.