=encoding utf8

=head1 NAME

optex - General purpose command option wrapper

=head1 VERSION

Version 1.06

=head1 SYNOPSIS

B<optex> I<command> [ B<-M>I<module> ] ...

or I<command> -> B<optex> symlink, or

B<optex> I<options> [ -l | -m ] ...

    --link,   --ln  create symlink
    --unlink, --rm  remove symlink
    --ls            list link files
    --rc            list rc files
    --nop, -x       disable option processing
    --[no]module    disable module option on arguments

=cut
=head1 DESCRIPTION

B<optex> is a general purpose command option handling wrapper
utilizing Perl module L<Getopt::EX>.  It enables user to define their
own option aliases for any commands on the system, and provide module
style extensibility.

Target command is given as an argument:

    % optex command

or as a symbolic linked file to B<optex>:

    command -> optex

If the configuration file F<~/.optex.d/>I<command>F<.rc> exists, it is
evaluated before execution and command arguments are pre-processed
using it.


=head2 OPTION ALIASES

Think of macOS's C<date> command, which does not have C<-I[TIMESPEC]>
option.  Using B<optex>, these can be implemented by preparing
following setting in F<~/.optex.d/date.rc> file.

    option -I        -Idate
    option -Idate    +%F
    option -Iseconds +%FT%T%z
    option -Iminutes +%FT%H:%M%z
    option -Ihours   +%FT%H%z

    option --iso-8601         -I
    option --iso-8601=date    -Idate
    option --iso-8601=seconds -Iseconds
    option --iso-8601=minutes -Iminutes
    option --iso-8601=hours   -Ihours

Then next command will work as expected.

    % optex date -Iseconds

If a symbolic link C<< date -> optex >> is found in command search
path, you can use it just same as standard command, but with
unsupported options.

    % date -Iseconds

Common configuration is stored in F<~/.optex.d/default.rc> file, and
those rules are applied to all commands executed through B<optex>.

Actually, C<--iso-8601> option can be defined simpler as this:

    option --iso-8601 -I$<shift>

This works fine almost always, but fails with sole C<--iso-8601>
option preceding other option like this:

    % date --iso-8601 -u

=head2 COMMAND ALIASES

B<optex>'s command alias is no different from the alias function of
shell, but it is effective in that it can be executed as a command
from a tool or script, and can be managed collectively in a
configuration file.

Command aliases can be set in the configuration file
(F<~/.optex.d/config.toml>) like this:

    [alias]
        tc = "optex -Mtextconv"

You can make symbolic link from C<tc> to C<optex> like this:

    % optex --ln tc

And include F<$HOME/.optex.d/bin> in your C<PATH> evnironment.

The C<textconv> module can be used to convert files given as arguments
to plain text.  Defined in this way, Word files can be compared as
follows.

    % tc diff A.docx B.docx

Alias name is used to find rc file and module directory.  In the above
example, F<~/.optex.d/tc.rc> and F<~/.optex.d/tc/> will be referred.

It is also possible to write shell scripts in the config file.  The
following example implements the C-shell C<repeat> command.

    [alias]
            repeat = [ 'bash', '-c', '''
                while getopts 'c:i:' OPT; do
                    case $OPT in
                        c) count=$OPTARG;;
                        i) sleep=$OPTARG;;
                    esac
                done; shift $((OPTIND - 1))
                case $1 in
                    [0-9]*) count=$1; shift;;
                esac
                while ((count--)); do
                    eval "$*"
                    [ "$sleep" ] && (( count > 0 )) && sleep $sleep
                done
            ''', 'repeat' ]

Read L<CONFIGURATION FILE> section.

=head2 MACROS

Complex string can be composed using macro C<define>.  Next example is
an awk script to count vowels in the text, to be declared in file
F<~/.optex.d/awk.rc>.

    define __delete__ /[bcdfgkmnpsrtvwyz]e( |$)/
    define __match__  /ey|y[aeiou]*|[aeiou]+/
    define __count_vowels__ <<EOS
    {
        s = tolower($0);
        gsub(__delete__, " ", s);
        for (count=0; match(s, __match__); count++) {
            s=substr(s, RSTART + RLENGTH);
        }
        print count " " $0;
    }
    EOS
    option --vowels __count_vowels__

This can be used like this:

    % awk --vowels /usr/share/dict/words

When setting complex option, C<expand> directive is useful.  C<expand>
works almost same as C<option>, but effective only within the file
scope, and not available for command line option.

    expand repository	( -name .git -o -name .svn -o -name RCS )
    expand no_dots	! -name .*
    expand no_version	! -name *,v
    expand no_backup	! -name *~
    expand no_image 	! -iname *.jpg  ! -iname *.jpeg \
			! -iname *.gif  ! -iname *.png
    expand no_archive	! -iname *.tar  ! -iname *.tbz  ! -iname *.tgz
    expand no_pdf	! -iname *.pdf

    option --clean \
            repository -prune -o \
            -type f \
            no_dots \
            no_version no_backup \
            no_image \
            no_archive \
            no_pdf

    % find . --clean -print


=head2 MODULES

B<optex> also supports module extension.  In the example of C<date>,
module file is found at F<~/.optex.d/date/> directory.  If default
module, F<~/.optex.d/date/default.pm> exists, it is loaded
automatically on every execution.

This is a normal Perl module, so package declaration and the final
true value is necessary.  Between them, you can put any kind of Perl
code.  For example, next program set environment variable C<LANG> to
C<C> before executing C<date> command.

    package default;
    $ENV{LANG} = 'C';
    1;

    % /bin/date
    2017年 10月22日 日曜日 18時00分00秒 JST

    % date
    Sun Oct 22 18:00:00 JST 2017

Other modules are loaded using C<-M> option.  Unlike other options,
C<-M> have to be placed at the beginning of argument list.  Module
files in F<~/.optex.d/date/> directory are used only for C<date>
command.  If the module is placed on F<~/.optex.d/> directory, it can
be used from all commands.

If you want use C<-Mes> module, make a file F<~/.optex.d/es.pm> with
following content.

    package es;
    $ENV{LANG} = 'es_ES';
    1;

    % date -Mes
    domingo, 22 de octubre de 2017, 18:00:00 JST

When the specified module was not found in library path, B<optex>
ignores the option and stops argument processing immediately.  Ignored
options are passed through to the target command.

Module is also used with subroutine call.  Suppose
F<~/.optex.d/env.pm> module look like:

    package env;
    sub setenv {
        while (($a, $b) = splice @_, 0, 2) {
            $ENV{$a} = $b;
        }
    }
    1;

Then it can be used in more generic fashion.  In the next example,
first format is easy to read, but second one is more easy to type
because it does not have special characters to be escaped.

    % date -Menv::setenv(LANG=de_DE) # need shell quote
    % date -Menv::setenv=LANG=de_DE  # alternative format
    So 22 Okt 2017 18:00:00 JST

Option aliases can be also declared in the module, at the end of file,
following special literal C<__DATA__>.  Using this, you can prepare
multiple set of options for different purposes.  Think about generic
B<i18n> module:

    package i18n;
    1;
    __DATA__
    option --cn -Menv::setenv(LANG=zh_CN) // 中国語 - 簡体字
    option --tw -Menv::setenv(LANG=zh_TW) // 中国語 - 繁体字
    option --us -Menv::setenv(LANG=en_US) // 英語
    option --fr -Menv::setenv(LANG=fr_FR) // フランス語
    option --de -Menv::setenv(LANG=de_DE) // ドイツ語
    option --it -Menv::setenv(LANG=it_IT) // イタリア語
    option --jp -Menv::setenv(LANG=ja_JP) // 日本語
    option --kr -Menv::setenv(LANG=ko_KR) // 韓国語
    option --br -Menv::setenv(LANG=pt_BR) // ポルトガル語 - ブラジル
    option --es -Menv::setenv(LANG=es_ES) // スペイン語
    option --ru -Menv::setenv(LANG=ru_RU) // ロシア語

This can be used like:

    % date -Mi18n --tw
    2017年10月22日 週日 18時00分00秒 JST

You can declare autoload module in your F<~/.optex.d/optex.rc> like:

    autoload -Mi18n --cn --tw --us --fr --de --it --jp --kr --br --es --ru

Then you can use them without module option.  In this case, option
C<--ru> is replaced by C<-Mi18n --ru> automatically.

    % date --ru
    воскресенье, 22 октября 2017 г. 18:00:00 (JST)

Module C<i18n> is implemented as L<Getopt::EX::i18n> and included in
this distribution.  So it can be used as above without additional
installation.

Modules can also define built-in options using C<builtin> directive in
the C<__DATA__> section.  Built-in options are processed by
L<Getopt::Long> and must be specified before the target command name.
For example:

    optex -Mxform --xform-visible=2 cat file

Here C<--xform-visible> is a built-in option defined in the C<xform>
module.

=head1 STANDARD MODULES

Standard modules are installed at C<App::optex>, and they can be
addressed with and without C<App::optex> prefix.

=over 4

=item -MB<help>

Print available option list.  Option name is printed with substitution
form, or help message if defined.  Use B<-x> option to omit help
message.

Option B<--man> or B<-h> will print document if available.  Option
B<-l> will print module path.  Option B<-m> will show the module
itself.  When used after other modules, print information about the
last declared module.  Next command show the document about B<second>
module.

    % optex -Mfirst -Msecond -Mhelp --man

=item -MB<debug>

Print debug messages.

=item -MB<util::argv>

Module to manipulate command argument.
See L<App::optex::util::argv> for detail.

=item -MB<util::filter>

Module to implement command input/output filters.
See L<App::optex::util::filter> for detail.

=back

=head1 Getopt::EX MODULES

In addition to its own modules, B<optex> can also use C<Getopt::EX>
modules.  The standard C<Getopt::EX> modules installed are these.

=over 4

=item -MB<i18n> (L<Getopt::EX::i18n>)

You can display a Greek calendar by doing the following:

    optex -Mi18n cal --gr

=back

=head1 OPTIONS

These options are not effective when B<optex> was executed from
symbolic link.

=over 4


=item B<--link>, B<--ln> [ I<command> ]

Create symbolic link in F<~/.optex.d/bin> directory.


=item B<--unlink>, B<--rm> [ B<-f> ] [ I<command> ]

Remove symbolic link in F<~/.optex.d/bin> directory.


=item B<--ls> [ B<-l> ] [ I<command> ]

List symbolic link files in F<~/.optex.d/bin> directory.


=item B<--rc> [ B<-l> ] [ B<-m> ] [ I<command> ]

List rc files in F<~/.optex.d> directory.


=item B<--nop>, B<-x> I<command>

Stop option manipulation.  Use full pathname otherwise.


=item B<-->[B<no>]B<module>

B<optex> deals with module option (-M) on target command by default.
However, there is a command which also uses same option for own
purpose.  Option B<--nomodule> disables that behavior.  Other option
interpretation is still effective, and there is no problem using
module option in rc or module files.


=item B<--exit> I<status>

Usually B<optex> exits with status of executed command.  This option
override it and force to exit with specified status code.


=back


=head1 CONFIGURATION FILE

When starting up, B<optex> reads configuration file
F<~/.optex.d/config.toml> which is supposed to be written in TOML
format.

=head2 PARAMETERS

=over 4

=item B<no-module>

Set commands for which B<optex> does not interpret module option
B<-M>.  If the target command is found in this list, it is executed as
if option B<--no-module> is given to B<optex>.

    no-module = [
        "greple",
        "pgrep",
    ]

=item B<alias>

Set command aliases.  Example:

    [alias]
        pgrep = [ "greple", "-Mperl", "--code" ]
        hello = "echo -n 'hello world!'"

Command alias can be invoked either from symbolic link and command
argument.

=item B<include>

Load extra TOML fragments before applying the main configuration.
Accepts either a string or an array.  Each entry may be a literal path
or a glob pattern.  Tilde is expanded, and relative paths are resolved
against the file that declared the include.  Includes are processed
depth-first; hashes merge recursively, arrays append, and scalars use
last-in-wins semantics.  The main F<config.toml> is applied last so it
can override included values.

    include = [
        "~/.optex.d/config.d/*.toml",
        "local.toml",
    ]

Include directives can nest; cycles (including self-globs) are detected
and reported as errors.

=back


=head1 FILES AND DIRECTORIES

=over 4


=item F<PERLLIB/App/optex>

System module directory.


=item F<~/.optex.d/>

Personal root directory.


=item F<~/.optex.d/config.toml>

Configuration file.


=item F<~/.optex.d/default.rc>

Common startup file.


=item F<~/.optex.d/>I<command>F<.rc>

Startup file for I<command>.


=item F<~/.optex.d/>I<command>F</>

Module directory for I<command>.


=item F<~/.optex.d/>I<command>F</default.pm>

Default module for I<command>.


=item F<~/.optex.d/bin>

Default directory to store symbolic links.

This is not necessary, but it seems a good idea to make special
directory to contain symbolic links for B<optex>, placing it in your
command search path.  Then you can easily add/remove it from the path,
or create/remove symbolic links.

=back


=head1 ENVIRONMENT

=over 4

=item OPTEX_ROOT

Override default root directory F<~/.optex.d>.

=item OPTEX_CONFIG

Override default configuration file F<OPTEX_ROOT/config.toml>.

=item OPTEX_MODULE_PATH

Set module paths separated by colon (C<:>).  These are inserted before
standard path.

=item OPTEX_BINDIR

Override default symbolic link directory F<OPTEX_ROOT/bin>.

=item OPTEX_SCRIPT_PATH

Specify the path to use when creating symbolic links with C<--ln>.
If not set, C<$0> is used.  This is useful when B<optex> is invoked
through a wrapper script (e.g., Homebrew installation) and you want
the symbolic links to point to the wrapper rather than the actual
script.

=back


=head1 SEE ALSO

L<Getopt::EX>, L<Getopt::EX::Loader>, L<Getopt::EX::Module>

L<App::optex::textconv>

L<App::optex::xform>

=head1 AUTHOR

Kazumasa Utashiro


=head1 LICENSE

You can redistribute it and/or modify it under the same terms
as Perl itself.

Copyright ©︎ 2017-2026 Kazumasa Utashiro


=cut
