The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Locale::Maketext::Extract - Extract translatable strings from source

VERSION

version 1.00

SYNOPSIS

my $Ext = Locale::Maketext::Extract->new;
$Ext->read_po('messages.po');
$Ext->extract_file($_) for <*.pl>;

# Set $entries_are_in_gettext_format if the .pl files above use
# loc('%1') instead of loc('[_1]')
$Ext->compile($entries_are_in_gettext_format);

$Ext->write_po('messages.po');

-----------------------------------

### Specifying parser plugins ###

my $Ext = Locale::Maketext::Extract->new(

    # Specify which parser plugins to use
    plugins => {

        # Use Perl parser, process files with extension .pl .pm .cgi
        perl => [],

        # Use YAML parser, process all files
        yaml => ['*'],

        # Use TT2 parser, process files with extension .tt2 .tt .html
        # or which match the regex
        tt2  => [
            'tt2',
            'tt',
            'html',
            qr/\.tt2?\./
        ],

        # Use My::Module as a parser for all files
        'My::Module' => ['*'],

    },

    # Warn if a parser can't process a file or problems loading a plugin
    warnings => 1,

    # List processed files
    verbose => 1,

);

DESCRIPTION

This module can extract translatable strings from files, and write them back to PO files. It can also parse existing PO files and merge their contents with newly extracted strings.

A command-line utility, xgettext.pl, is installed with this module as well.

The format parsers are loaded as plugins, so it is possible to define your own parsers.

Following formats of input files are supported:

Perl source files (plugin: perl)

Valid localization function names are: translate, maketext, gettext, l, loc, x, _ and __.

For a slightly more accurate, but much slower Perl parser, you can use the PPI plugin. This does not have a short name (like perl), but must be specified in full.

HTML::Mason (Mason 1) and Mason (Mason 2) (plugin: mason)

HTML::Mason (aka Mason 1) Strings inside <&|/l>...</&> and <&|/loc>...</&> are extracted.

Mason (aka Mason 2) Strings inside <% $.floc { %>...</%> or <% $.fl { %>...</%> or <% $self->floc { %>...</%> or <% $self->fl { %>...</%> are extracted.

Template Toolkit (plugin: tt2)

Valid forms are:

[% | l(arg1,argn) %]string[% END %]
[% 'string' | l(arg1,argn) %]
[% l('string',arg1,argn) %]

FILTER and | are interchangeable
l and loc are interchangeable
args are optional
Text::Template (plugin: text)

Sentences between STARTxxx and ENDxxx are extracted individually.

YAML (plugin: yaml)

Valid forms are _"string" or _'string', eg:

title: _"My title"
desc:  _'My "quoted" string'

Quotes do not have to be escaped, so you could also do:

desc:  _"My "quoted" string"
HTML::FormFu (plugin: formfu)

HTML::FormFu uses a config-file to generate forms, with built in support for localizing errors, labels etc.

We extract the text after _loc: : content_loc: this is the string message_loc: ['Max string length: [_1]', 10]

Generic Template (plugin: generic)

Strings inside {{...}} are extracted.

METHODS

Constructor

new()

new(
    plugins   => {...},
    warnings  => 1 | 0,
    verbose   => 0 | 1 | 2 | 3,
)

See "Plugins", "Warnings" and "Verbose" for details

Plugins

$ext->plugins({...});

Locale::Maketext::Extract uses plugins (see below for the list) to parse different formats.

Each plugin can also specify which file types it can parse.

# use only the YAML plugin
# only parse files with the default extension list defined in the plugin
# ie .yaml .yml .conf

$ext->plugins({
    yaml => [],
})


# use only the Perl plugin
# parse all file types

$ext->plugins({
    perl => '*'
})

$ext->plugins({
    tt2  => [
        'tt',              # matches base filename against /\.tt$/
        qr/\.tt2?\./,      # matches base filename against regex
        \&my_filter,       # codref called
    ]
})

sub my_filter {
    my ($base_filename,$path_to_file) = @_;

    return 1 | 0;
}

# Specify your own parser
# only parse files with the default extension list defined in the plugin

$ext->plugins({
    'My::Extract::Parser'  => []
})

By default, if no plugins are specified, it first tries to determine which plugins are intended specifically for the file type and uses them. If no such plugins are found, it then uses all of the builtin plugins, overriding the file types specified in each.

Available plugins

perl : Locale::Maketext::Extract::Plugin::Perl

For a slightly more accurate but much slower Perl parser, you can use the PPI plugin. This does not have a short name, but must be specified in full, ie: Locale::Maketext::Extract::Plugin::PPI

tt2 : Locale::Maketext::Extract::Plugin::TT2
yaml : Locale::Maketext::Extract::Plugin::YAML
formfu : Locale::Maketext::Extract::Plugin::FormFu
mason : Locale::Maketext::Extract::Plugin::Mason
text : Locale::Maketext::Extract::Plugin::TextTemplate
generic : Locale::Maketext::Extract::Plugin::Generic

Also, see Locale::Maketext::Extract::Plugin::Base for details of how to write your own plugin.

Warnings

Because the YAML and TT2 plugins use proper parsers, rather than just regexes, if a source file is not valid and it is unable to parse the file, then the parser will throw an error and abort parsing.

The next enabled plugin will be tried.

By default, you will not see these errors. If you would like to see them, then enable warnings via new(). All parse errors will be printed to STDERR.

Also, if developing your own plugin, turn on warnings to see any errors that result from loading your plugin.

Verbose

If you would like to see which files have been processed, which plugins were used, and which strings were extracted, then enable verbose. If no acceptable plugin was found, or no strings were extracted, then the file is not listed:

   $ext = Locale::Extract->new( verbose => 1 | 2 | 3);

OR
   xgettext.pl ... -v           # files reported
   xgettext.pl ... -v -v        # files and plugins reported
   xgettext.pl ... -v -v -v     # files, plugins and strings reported

Accessors

header, set_header
lexicon, set_lexicon, msgstr, set_msgstr
entries, set_entries, entry, add_entry, del_entry
compiled_entries, set_compiled_entries, compiled_entry,
add_compiled_entry, del_compiled_entry
clear

PO File manipulation

method read_po ($file)

method write_po ($file, $add_format_marker?)

Extraction

extract
extract_file

Compilation

compile($entries_are_in_gettext_style?)

Merges the entries into compiled_entries.

If $entries_are_in_gettext_style is true, the previously extracted entries are assumed to be in the Gettext style (e.g. %1).

Otherwise they are assumed to be in Maketext style (e.g. [_1]) and are converted into Gettext style before merging into compiled_entries.

The entries are not cleared after each compilation; use -set_entries()> to clear them if you need to extract from sources with varying styles.

normalize_space

Lexicon accessors

msgids, has_msgid,
msgstr, set_msgstr
msg_positions, msg_variables, msg_format, msg_out

Internal utilities

_default_header
_maketext_to_gettext
_escape
_format
_plugins_specifically_for_file

ACKNOWLEDGMENTS

Thanks to Jesse Vincent for contributing to an early version of this module.

Also to Alain Barbet, who effectively re-wrote the source parser with a flex-like algorithm.

SEE ALSO

xgettext.pl, Locale::Maketext, Locale::Maketext::Lexicon

AUTHORS

Audrey Tang <cpan@audreyt.org>

COPYRIGHT

Copyright 2003-2013 by Audrey Tang <cpan@audreyt.org>.

This software is released under the MIT license cited below.

The "MIT" License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

AUTHORS

  • Clinton Gormley <drtech@cpan.org>

  • Audrey Tang <cpan@audreyt.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2014 by Audrey Tang.

This is free software, licensed under:

The MIT (X11) License