The m17n Library: Data format of the m17n database

# Data format of the m17n database

This section describes formats of these data supplied by the m17n database.

- General -- General Format
- CharsetList -- List of character set definitions
- CodingList -- List of coding system definitions
- Dir -- List of data in a database directory.
- FLT -- Font Layout Table
- FontEncoding -- Font Encoding
- FontSize -- Font Size
- Fontset -- Fontset
- IM -- Input Method

## General Format

### DESCRIPTION

The mdatabase_load() function returns the data specified by tags in the form of plist if the first tag is not `Mchartable` nor `Mcharset`. The keys of the returned plist are limited to `Minteger`, `Msymbol`, `Mtext`, and `Mplist`. The type of the value is unambiguously determined by the corresponding key. If the key is `Minteger`, the value is an integer. If the key is `Msymbol`, the value is a symbol. And so on.

A number of expressions are possible to represent a plist. For instance, we can use the form `(K1:V1, K2:V2, ..., Kn:Vn)` to represent a plist whose first property key and value are K1 and V1, second key and value are K2 and V2, and so on. However, we can use a simpler expression here because the types of plists used in the m17n database are fairly restricted.

Hereafter, we use an expression, which is similar to S-expression, to represent a plist. (Actually, the default database loader of the m17n library is designed to read data files written in this expression.)

The expression consists of one or more elements. Each element represents a property, i.e. a single element of a plist.

Elements are separated by one or more whitespaces, i.e. a space (code 32), a tab (code 9), or a newline (code 10). Comments begin with a semicolon (`;`) and extend to the end of the line.

The key and the value of each property are determined based on the type of the element as explained below.

- INTEGER

  An element that matches the regular expression `-?[0-9]+` or `0[xX][0-9A-Fa-f]+` represents a property whose key is `Minteger`. An element matching the former expression is interpreted as an integer in decimal notation, and one matching the latter is interpreted as an integer in hexadecimal notation. The value of the property is the result of interpretation.

  For instance, the element `0xA0` represents a property whose value is 160 in decimal.

- SYMBOL

  An element that matches the regular expression `[^-0-9(]([^\()]|\.)+` represents a property whose key is `Msymbol`. In the element, `\t`, `\n`, `\r`, and `\e` are replaced with tab (code 9), newline (code 10), carriage return (code 13), and escape (code 27) respectively. Other characters following a backslash is interpreted as it is. The value of the property is the symbol having the resulting string as its name.

  For instance, the element `abc\ def` represents a property whose value is the symbol having the name "abc def".

- MTEXT

  An element that matches the regular expression `"([^"]|\")*"` represents a property whose key is `Mtext`. The backslash escape explained above also applies here. Moreover, each part in the element matching the regular expression `\[xX][0-9A-Fa-f][0-9A-Fa-f]` is replaced with its hexadecimal interpretation.

  After having resolved the backslash escapes, the byte sequence between the double quotes is interpreted as a UTF-8 sequence and decoded into an M-text. This M-text is the value of the property.

- PLIST

  Zero or more elements surrounded by a pair of parentheses represent a property whose key is `Mplist`. Whitespaces before and after a parenthesis can be omitted. The value of the property is a plist, which is the result of recursive interpretation of the elements between the parentheses.

### SYNTAX NOTATION

In an explanation of a plist format of data, a BNF-like notation is used. In the notation, non-terminals are represented by a string of uppercase letters (including '-' in the middle), terminals are represented by a string surrounded by '"'. Special non-terminals INTEGER, SYMBOL, MTEXT and PLIST represents property integer, symbol, M-text, or plist respectively.

### EXAMPLE

Here is an example of database data that is read into a plist of this simple format:

    DATA-FORMAT ::=
        [ INTEGER | SYMBOL | MTEXT | FUNC ] *

    FUNC ::=
        '(' FUNC-NAME FUNC-ARG * ')'

    FUNC-NAME ::=
        SYMBOL

    FUNC-ARG ::=
        INTEGER | SYMBOL | MTEXT | '(' FUNC-ARG ')'

For instance, a data file that contains this text matches the above syntax:

    abc 123 (pqr 0xff) "m\"text" (_\\_ ("string" xyz) -456)

and is read into this plist:

    1st element: key: Msymbol,  value: abc
    2nd element: key: Minteger, value: 123
    3rd element: key: Mplist,   value: a plist of these elements:
        1st element: key Msymbol,  value: pgr
        2nd element: key Minteger, value: 255
    4th element: key: Mtext,    value: m"text
    5th element: key: Mplist,   value: a plist of these elements:
        1st element: key: Msymbol, value: _\_
        2nd element: key: Mplist,  value: a plist of these elements:
            1st element: key: Mtext,    value: string
    	2nd element: key: Msymbol,  value: xyz
    	3rd element: key: Minteger, value: -456

## List of character set definitions

### DESCRIPTION

The m17n library loads a list of charset definitions from the data of tag <charset-list>. The data is loaded as a plist of this format.

    CHARSET-LIST ::= DEFINITION *

    DEFINITION ::= '(' NAME ( KEY VALUE ) * ')'

    NAME ::= SYMBOL

    KEY ::= SYMBOL

    VALUE ::= SYMBOL | INTEGER | MTEXT | PLIST

`NAME` is a name of a charset to define.

`KEY` and `VALUE` pair is a property given to the function mchar_define_charset() as an element of the second argument plist.

### SEE ALSO

mdbGeneral(5), mchar_define_charset()

## List of coding system definitions

### DESCRIPTION

The m17n library loads a list of coding system definitions from the m17n database by the tags <coding-list> at initialization time. The data is loaded as a plist of this format.

    CODING-LIST ::= DEFINITION *

    DEFINITION ::= '(' NAME ( KEY VALUE ) * ')'
    NAME ::= SYMBOL

    KEY ::= SYMBOL

    VALUE ::= SYMBOL | INTEGER | MTEXT | PLIST

`NAME` is a name of a coding system to define.

`KEY` and `VALUE` pair is a property given to the function mconv_define_coding() as the second argument.

### SEE ALSO

mdbGeneral(5), mconv_define_coding()

## List of data in a database directory.

### DESCRIPTION

The m17n library loads a list of definitions of data of the m17n database from files of name "mdb.dir" in each database directory at initialization time. The plist format of this file is as follows:

    MDB-DIR ::= DEFINITION *

    DEFINITION ::= '(' TAG0 [ TAG1 [ TAG2 [ TAG3 ] ] ] FILE [ VERSION ]')'

    TAGn ::= SYMBOL

    FILE ::= MTEXT

    VERSION ::= MTEXT

If TAG0 is neither `charset' nor `char-table', and TAGn (n > 0) is a symbol `*', FILE can contain a wildcard charater, and all files matching FILE accoding to the rules used by the shell are the target of database files. In that case, each file must contain SELF-DEFINITION which is a plist element providing the actual TAGn values by the form:

    SELF-DEFINITION ::= '(' TAG0 TAG1 TAG2 TAG3 [ VERSION ] ')'

For instance, if a database directory contains these files:

    zh-py.mim:
    (input-method zh py)

    ko-han2.mim:
    (input-method ko han2)

these lines in "mdb.dir":

    (input-method zh py "zh-py.mim")
    (input-method ko han2 "ko-han2.mim")

can be shortened to this single line:

    (input-method * "*.mim")

VERSION is a required version number of the m17n library. The format is "XX.YY.ZZ" where XX is a major version number, YY is a minor version number, and ZZ is a patch level.

## Font Layout Table

### DESCRIPTION

For simple scripts, the rendering engine converts character codes into glyph codes one by one by consulting the encoding of each selected font. But, to render text that requires complicated layout (e.g. Thai and Indic scripts), one to one conversion is not sufficient. A sequence of characters may have to be drawn as a single ligature. Some glyphs may have to be drawn at 2-dimensionally shifted positions.

To handle those complicated scripts, the m17n library uses Font Layout Tables (FLTs for short). The FLT driver interprets an FLT and converts a character sequence into a glyph sequence that is ready to be passed to the rendering engine.

An FLT can contain information to extract a grapheme cluster from a character sequence and to reorder the characters in the cluster, in addition to information found in OpenType Layout Tables (CMAP, GSUB, and GPOS).

An FLT is a cascade of one or more conversion stages. In each stage, a sequence is converted into another sequence to be read in the next stage. The length of sequences may differ from stage to stage. Each element in a sequence has the following integer attributes.

- code

  In the first conversion stage, this is the character code in the original character sequence. In the last stage, it is the glyph code passed to the rendering engine. In other cases, it is an intermediate glyph code.

- category

  The category code defined in the `CATEGORY-TABLE` of the current stage, or defined in the one of the former stages and not overwritten by later stages.

- combining-spec

  If nonzero, it specifies how to combine this (intermediate) glyph with the previous one.

- left-padding-flag

  If nonzero, it instructs the rendering function to insert a padding space before this (intermediate) glyph so that the glyph does not overlap with the previous one.

- right-padding-flag

  If nonzero, it instructs the rendering function to insert a padding space after this (intermediate) glyph so that the glyph does not overlap with the next one.

When the layout engine draws text, it at first determines a font and an FLT for each character in the text. For each subsequence of characters that use the same font and FLT, the layout engine generates a corresponding intermediate glyph sequence. The code attribute of each element in the intermediate glyph sequence is its character code, and all other attributes are zeros. This sequence is processed in the first stage of FLT as the current run (substring).

Each stage works as follows.

At first, if the stage has a `CATEGORY-TABLE`, the category of each glyph in the current run is updated. If there is a glyph that has no category, the current run ends before that glyph.

Then, the default values of code-offset, combining-spec, and left-padding-flag of this stage are initialized to zero.

Next, the initial conversion rule of the stage is applied to the current run.

Lastly, the current run is replaced with the newly produced (intermediate) glyph sequence.

### SYNTAX and SEMANTICS

The m17n library loads an FLT from the m17n database using the tag <font, layouter, FLT-NAME>. The date format of an FLT is as follows:

    FONT-LAYOUT-TABLE ::= FLT-DECLARATION ? STAGE0 STAGE *

    FLT-DECLARATION ::= '(' 'font' 'layouter' FLT-NAME nil PROP * ')'
    FLT-NAME ::= SYMBOL
    PROP :: = VERSION | FONT
    VERSION ::= '(' 'version' MTEXT ')'
    FONT ::= '(' 'font' FONT-SPEC ')'
    FONT-SPEC ::=
         '(' [[ FOUNDRY FAMILY
               [ WEIGHT [ STYLE [ STRETCH [ ADSTYLE ]]]]]
             REGISTRY ]
    	 [ OTF-SPEC ] [ LANG-SPEC ] ')'

    STAGE0 ::= CATEGORY-TABLE GENERATOR

    STAGE ::= CATEGORY-TABLE ? GENERATOR

    CATEGORY-TABLE ::= '(' 'category' CATEGORY-SPEC + ')'

    CATEGORY-SPEC ::= '(' CODE CATEGORY ')'
                      | '(' CODE CODE CATEGORY ')'

    CODE ::= INTEGER

    CATEGORY ::= INTEGER

In the definition of `CATEGORY-SPEC`, `CODE` is a glyph code, and `CATEGORY` is ASCII code of an upper or lower letter, i.e. one of 'A', ... 'Z', 'a', .. 'z'.

The first form of `CATEGORY-SPEC` assigns `CATEGORY` to a glyph whose code is `CODE`. The second form assigns `CATEGORY` to glyphs whose code falls between the two `CODEs`.

    GENERATOR ::= '(' 'generator' RULE MACRO-DEF * ')'

    RULE ::= REGEXP-BLOCK | MATCH-BLOCK | SUBST-BLOCK | COND-BLOCK
             FONT-FACILITY-BLOCK | DIRECT-CODE | COMBINING-SPEC | OTF-SPEC
             | PREDEFINED-RULE | MACRO-NAME

    MACOR-DEF ::= '(' MACRO-NAME RULE + ')'

Each `RULE` specifies glyphs to be consumed and glyphs to be produced. When some glyphs are consumed, they are taken away from the current run. A rule may fail in some condition. If not described explicitly to fail, it should be regarded that the rule succeeds.

    DIRECT-CODE ::= INTEGER

This rule consumes no glyph and produces a glyph which has the following attributes:

- code : `INTEGER` plus the default code-offset
- combining-spec : default value
- left-padding-flag : default value
- right-padding-flag : zero

After having produced the glyph, the default code-offset, combining-spec, and left-padding-flag are all reset to zero.

    PREDEFINED-RULE ::= '=' | '*' | '<' | '>' | '|' | '[' | ']'

They perform actions as follows.

- `=`

  This rule consumes the first glyph in the current run and produces the same glyph. It fails if the current run is empty.

- `*`

  This rule repeatedly executes the previous rule. If the previous rule fails, this rule does nothing and fails.

- `<`

  This rule specifies the start of a grapheme cluster.

- `>`

  This rule specifies the end of a grapheme cluster.

- `@`[

  This rule sets the default left-padding-flag to 1. No glyph is consumed. No glyph is produced.

- `@`]

  This rule changes the right-padding-flag of the lastly generated glyph to 1. No glyph is consumed. No glyph is produced.

- ``|

  This rule consumes no glyph and produces a special glyph whose category is ' ' and other attributes are zero. This is the only rule that produces that special glyph.

    REGEXP-BLOCK ::= '(' REGEXP RULE * ')'

    REGEXP ::= MTEXT

`MTEXT` is a regular expression that should match the sequence of categories of the current run. If a match is found, this rule executes `RULEs` temporarily limiting the current run to the matched part. The matched part is consumed by this rule.

Parenthesized subexpressions, if any, are recorded to be used in `MATCH-BLOCK` that may appear in one of `RULEs`.

If no match is found, this rule fails.

    MATCH-BLOCK ::= '(' MATCH-INDEX RULE * ')'

    MATCH-INDEX ::= INTEGER

`MATCH-INDEX` is an integer specifying a parenthesized subexpression recorded by the previous `REGEXP-BLOCK`. If such a subexpression was found by the previous regular expression matching, this rule executes `RULEs` temporarily limiting the current run to the matched part of the subexpression. The matched part is consumed by this rule.

If no match was found, this rule fails.

If this is the first rule of the stage, `MATCH-INDEX` must be 0, and it matches the whole current run.

    SUBST-BLOCK ::= '(' SOURCE-PATTERN RULE * ')'

    SOURCE-PATTERN ::= '(' CODE + ')'
                       | (' 'range' CODE CODE ')'

If the sequence of codes of the current run matches `SOURCE-PATTERN`, this rule executes `RULEs` temporarily limiting the current run to the matched part. The matched part is consumed.

The first form of `SOURCE-PATTERN` specifies a sequence of glyph codes to be matched. In this case, this rule resets the default code-offset to zero.

The second form specifies a range of codes that should match the first glyph code of the code sequence. In this case, this rule sets the default code-offset to the first glyph code minus the first `CODE` specifying the range.

If no match is found, this rule fails.

    FONT-FACILITY-BLOCK ::= '(' FONT-FACILITY RULE * ')'
    FONT-FACILITY = '(' 'font-facility' CODE * ')'
    	      	| '(' 'font-facility' FONT-SPEC ')'

If the current font has glyphs for `CODEs` or matches with `FONT-SPEC`, this rule succeeds and `RULEs` are executed. Otherwise, this rule fails.

    COND-BLOCK ::= '(' 'cond' RULE + ')'

This rule sequentially executes `RULEs` until one succeeds. If no rule succeeds, this rule fails. Otherwise, it succeeds.

    OTF-SPEC ::= SYMBOL

`OTF-SPEC` is a symbol whose name specifies an instruction to the OTF driver. The name has the following syntax.

      OTF-SPEC-NAME ::= ':otf' SCRIPT LANGSYS ? GSUB-FEATURES ? GPOS-FEATURES ?

      SCRIPT ::= SYMBOL

      LANGSYS ::= '/' SYMBOL

      GSUB-FEATURES ::= '=' FEATURE-LIST ?

      GPOS-FEATURES ::= '+' FEATURE-LIST ?

      FEATURE-LIST ::= ( SYMBOL ',' ) * [ SYMBOL | '*' ]

Each `SYMBOL` specifies a tag name defined in the OpenType specification.

For `SCRIPT`, `SYMBOL` specifies a Script tag name (e.g. deva for Devanagari).

For `LANGSYS`, `SYMBOL` specifies a Language System tag name. If `LANGSYS` is omitted, the Default Language System table is used.

For `GSUB-FEATURES`, each `SYMBOL` in `FEATURE-LIST` specifies a GSUB Feature tag name to apply. '*' is allowed as the last item to specify all remaining features. If `SYMBOL` is preceded by '~' and the last item is '*', `SYMBOL` is excluded from the features to apply. If no `SYMBOL` is specified, no GSUB feature is applied. If `GSUB-FEATURES` itself is omitted, all GSUB features are applied.

When `OTF-SPEC` appears in a `FONT-SPEC`, `FEATURE-LIST` specifies features that the font must have (or must not have if preceded by '~'), and the last'*', even if exists, has no meaning.

The specification of `GPOS-FEATURES` is analogous to that of `GSUB-FEATURES`.

Please note that all the tags above must be 4 ASCII printable characters.

See the following page for the OpenType specification.
<http://www.microsoft.com/typography/otspec/default.htm>

    COMBINING ::= SYMBOL

`COMBINING` is a symbol whose name specifies how to combine the next glyph with the previous one. This rule sets the default combining-spec to an integer code that is unique to the symbol name. The name has the following syntax.

      COMBINING-NAME ::= VPOS HPOS OFFSET VPOS HPOS

      VPOS ::= 't' | 'c' | 'b' | 'B'

      HPOS ::= 'l' | 'c' | 'r'

      OFFSET :: = '.' | XOFF | YOFF XOFF ?

      XOFF ::= ('<' | '>') INTEGER ?

      YOFF ::= ('+' | '-') INTEGER ?

`VPOS` and `HPOS` specify the vertical and horizontal positions as described below.

                                    POINT VPOS HPOS
                                    ----- ---- ----
        0----1----2 <---- top       0     t    l
        |         |                 1     t    c
        |         |                 2     t    r
        |         |                 3     B    l
        9   10   11 <---- center    4     B    c
        |         |                 5     B    r
      --3----4----5-- <-- baseline  6     b    l
        |         |                 7     b    c
        6----7----8 <---- bottom    8     b    r
                                    9     c    l
        |    |    |                10     c    c
      left center right            11     c    r

The left figure shows 12 reference points of a glyph by numbers 0 to 11. The rectangle 0-6-8-2 is the bounding box of the glyph, the positions 3, 4, and 5 are on the baseline, 9-11 are on the vertical center of the box, 0-2 and 6-8 are on the top and on the bottom respectively. 1, 10, 4, and 7 are on the horizontal center of the box.

The right table shows how those reference points are specified by a pair of `VPOS` and `HPOS`.

The first `VPOS` and `HPOS` in the definition of `COMBINING-NAME` specify the reference point of the previous glyph, and the second `VPOS` and `HPOS` specify that of the next glyph. The next glyph is drawn so that these two reference points align.

`OFFSET` specifies the way of alignment in detail. If it is '.', the reference points are on the same position.

`XOFF` specifies how much the X position of the reference point of the next glyph should be shifted to the left ('<') or right ('>') from the previous reference point.

`YOFF` specifies how much the Y position of the reference point the next glyph should be shifted upward ('+') or downward ('-') from the previous reference point.

In both cases, `INTEGER` is the amount of shift expressed as a percentage of the font size, i.e., if `INTEGER` is 10, it means 10% (1/10) of the font size. If `INTEGER` is omitted, it is assumed that 5 is specified.

Once the next glyph is combined with the previous one, they are treated as a single combined glyph.

    MACRO-NAME ::= SYMBOL

`MACRO-NAME` is a symbol that appears in one of `MACRO-DEF`. It is exapanded to the sequence of the correponding `RULEs`.

### CONTEXT DEPENDENT BEHAVIOR

So far, it has been assumed that each sequence, which is drawn with a specific font, is context free, i.e. not affected by the glyphs preceding or following that sequence. This is true when sequence S1 is drawn with font F1 while the preceding sequence S0 unconditionally requires font F0.

      sequence                              S0      S1
      currently used font                   F0      F1
      usable font(s)                        F0      F1

Sometimes, however, a clear separation of sequences is not possible. Suppose that the preceding sequence S0 can be drawn not only with F0 but also with F1.

      sequence                              S0      S1
      currently used font                   F0      F1
      usable font(s)                        F0,F1   F1

In this case, glyphs used to draw the preceding S0 may affect glyph generation of S1. Therefore it is necessary to access information about S0, which has already been processed, when processing S1. Generation rules in the first stage (only in the first stage) accept a special regular expression to access already processed parts.

      "RE0 RE1"

`RE0` and `RE1` are regular expressions that match the preceding sequence S0 and the following sequence S1, respectively.

Pay attention to the space between the two regular expressions. It represents the special category ' ' (see above). Note that the regular expression above belongs to glyph generation rules using font F1, therefore not only RE1 but also RE0 must be expressed with the categories for F1. This means when the preceding sequence S0 cannot be expressed with the categories for F1 (as in the first example above) generation rules having these patterns never match.

### SEE ALSO

mdbGeneral(5), FLTs provided by the m17n database

## Font Encoding

### DESCRIPTION

The m17n library loads information about the encoding of each font form the m17n database by the tags <font, encoding>. The data is loaded as a plist of this format.

    FONT-ENCODING ::= PER-FONT *

    PER-FONT ::= '(' FONT-SPEC ENCODING [ REPERTORY ] ')'

    FONT-SPEC ::=
        '(' [ FOUNDRY FAMILY
        	  [ WEIGHT [ STYLE [ STRETCH [ ADSTYLE ]]]]]
    	REGISTRY ')'

    ENCODING ::= SYMBOL

`FONT-SPEC` is to specify properties of a font. `FOUNDRY` to `REGISTRY` are symbols corresponding to Mfoundry to Mregistry property of a font. See Font for the meaning of each property.

For instance, this `FONT-SPEC`:

        (nil alice0\ lao iso8859-1)

should be applied to all fonts whose family name is "alice0 lao", and registry is "iso8859-1".

`ENCODING` is a symbol representing a charset. A font matching `FONT-SPEC` supports all characters of the charset, and a character code is mapped to the corresponding glyph code of the font by this charset.

`REPERTORY` is a symbol representing a charset or "nil". Omitting it is the same as specifying `ENCODING` as `REPERTORY`. If it is not "nil", the charset specifies the repertory of the font, i.e, which character it supports. Otherwise, whether a specific character is supported by the font or not is asked to each font driver.

For so called Unicode fonts (registry is "iso10646-1"), it is recommended to specify "nil" as `REPERTORY` because such fonts usually supports only a subset of Unicode characters.

## Font Size

### DESCRIPTION

In some case, a font contains incorrect information about its size (typically in the case of a hacked TrueType font), which results in a bad text layout when such a font is used in combination with the other fonts. To overcome this problem, the m17n library loads information about font-size adjustment from the m17n database by the tags <font, resize>. The data is loaded as a plist of this format.

    FONT-SIZE-ADJUSTMENT ::= PER-FONT *

    PER-FONT ::= '(' FONT-SPEC ADJUST-RATIO ')'

    FONT-SPEC ::=
        '(' [ FOUNDRY FAMILY
        	  [ WEIGHT [ STYLE [ STRETCH [ ADSTYLE ]]]]]
    	REGISTRY ')'

    ADJUST-RATIO ::= INTEGER

`FONT-SPEC` is to specify properties of a font. `FOUNDRY` to `REGISTRY` are symbols corresponding to Mfoundry to Mregistry property of a font. See Font for the meaning of each property.

`ADJUST-RATIO` is an integer number specifying by percentage how much the font-size must be adjusted. For instance, this `PER-FONT`:

        ((devanagari-cdac) 150)

instructs the font handler of the m17n library to open a font of 1.5 times bigger than a requested size on opening a font whose registry is "devanagari-cdac".

## Fontset

### DESCRIPTION

The m17n library loads a fontset definition from the m17n database by the tags <fontset, FONTSET-NAME>. The plist format of the data is as follows:

    FONTSET ::= PER-SCRIPT * PER-CHARSET * FALLBACK *

    PER-SCRIPT ::= '(' SCRIPT PER-LANGUAGE + ')'

    PER-LANGUAGE ::= '(' LANGUAGE FONT-SPEC-ELEMENT + ')'

    PER-CHARSET ::= '(' CHARSET FONT-SPEC-ELEMENT + ')'

    FALLBACK ::= FONT-SPEC-ELEMENT

    FONT-SPEC-ELEMENT ::= '(' FONT-SPEC [ FLT-NAME ] ')'

    FONT-SPEC ::=
         '(' [ FOUNDRY FAMILY
               [ WEIGHT [ STYLE [ STRETCH [ ADSTYLE ]]]]]
             REGISTRY
    	 [ OTF-SPEC ] [ LANG-SPEC ] ')'

`SCRIPT` is a symbol of script name (e.g. latin, han) or `nil`. `LANGUAGE` is a two-letter symbol of language name code defined by ISO 639 (e.g. ja, zh) or `nil`.

`FONT-SPEC` is to specify properties of a font. `FOUNDRY` to `REGISTRY` are symbols corresponding to Mfoundry to Mregistry property of a font. See Font for the meaning of each property.

`OTF-SPEC` is a symbol specifing the required OTF features. The symbol name has the following syntax.

      OTF-SPEC-NAME ::= ':otf=' SCRIPT LANGSYS ? GSUB-FEATURES ? GPOS-FEATURES ?

      SCRIPT ::= SYMBOL
      LANGSYS ::= '/' SYMBOL

      GSUB-FEATURES ::= '=' FEATURE-LIST ?

      GPOS-FEATURES ::= '+' FEATURE-LIST ?

      FEATURE-LIST ::= '~' ? FEATURE ( ',' '~' ? FEATURE ',' )

Here, `FEATURE` is a four-letter Open Type feature.

`LANG-SPEC` is a symbol specifying the required language support. The symbol name has the following syntax.

      LANG-SPEC-NAME ::= ':lang=' LANG

Here, `LANG` is a two or three-letter ISO-639 language code.

`FLT-NAME` is a name of Font Layout Table (Font Layout Table).

### EXAMPLE

This is an example of `PER_SCRIPT`.

    (han
      (ja
        ((jisx0208.1983-0)))
      (zh
        ((gb2312.1980-0)))
      (nil
        ((big5-0))))

It instructs the font selector to use a font of registry "jisx0208.1983-0" for a "han" character (i.e. a character whose Mscript property is 'han') if the character has Mlanguage text property "ja" in an M-text and the character is in the repertories of such fonts. Otherwise, try a font of registry "gb2312.1980-0" or "big5-0". If that "han" character does not have Mlanguage text property, try all three fonts.

See the function mdraw_text() for the detail of how a font is selected.

## Input Method

### DESCRIPTION

The m17n library provides a driver for input methods that are dynamically loadable from the m17n database (see Input Method (basic) ).

This section describes the data format that defines those input methods.

### SYNTAX and SEMANTICS

The following data format defines an input method. The driver loads a definition from a file, a stream, etc. The definition is converted into the form of plist in the driver.

    INPUT-METHOD ::=
        IM-DECLARATION ? IM-DESCRIPTION ? TITLE ?
         VARIABLE-LIST ? COMMAND-LIST ?  MODULE-LIST ?
         MACRO-LIST ? MAP-LIST ? STATE-LIST ?

    IM-DECLARATION ::= '(' 'input-method' LANGUAGE NAME EXTRA-ID ? VERSION ? ')'
    LANGUAGE ::= SYMBOL
    NAME ::= SYMBOL
    EXTRA-ID ::= SYMBOL
    VERSION ::= '(' 'version' VERSION-NUMBER ')'

    IM-DESCRIPTION ::= '(' 'description' DESCRIPTION ')'
    DESCRIPTION ::= MTEXT-OR-GETTEXT | 'nil'
    MTEXT-OR-GETTEXT ::=  [ MTEXT | '(' '_' MTEXT ')']

    TITLE ::= '(' 'title' TITLE-TEXT ')'
    TITLE-TEXT ::= MTEXT

    VARIABLE-LIST ::= '(' 'variable' VARIABLE-DECLARATION * ')'
    VARIABLE-DECLARATION ::=  '(' VAR-NAME [ DESCRIPTION VALUE VALUE-CANDIDATE * ]')'
    VAR-NAME ::= SYMBOL
    VALUE ::= MTEXT | SYMBOL | INTEGER
    VALUE-CANDIDATE ::= VALUE | '(' RANGE-FROM RANGE-TO ')'
    RANGE-FROM ::= INTEGER
    RANGE-TO ::= INTEGER

    COMMAND-LIST ::= '(' 'command' COMMAND-DECLARATION * ')'
    COMMAND-DECLARATION ::=  '(' CMD-NAME [ DESCRIPTION KEYSEQ * ] ')'
    CMD-NAME ::= SYMBOL

`IM-DECLARATION` specifies the language and name of this input method.

When `LANGUAGE` is `t`, the use of the input method is not limited to one language.

When `NAME` is `nil`, the input method is not standalone, but is expected to be used in other input methods. In such cases, `EXTRA-ID` is required to identify the input method.

`VERSION` specifies the required minimum version number of the m17n library. The format is "XX.YY.ZZ" where XX is a major version number, YY is a minor version number, and ZZ is a patch level.

`DESCRIPTION`, if not nil, specifies the description text of an input method, a variable or a command. If `MTEXT-OR-GETTEXT` takes the second form, the text is translated according to the current locale by "gettext" (if the translation is provided).

`TITLE-TEXT` is a text displayed on the screen when this input method is active.

There is one special input method file "global.mim" that declares common variables and commands. The input method driver always loads this file and other input methods can inherit the variables and the commands.

`VARIABLE-DECLARATION` declares a variable used in this input method. If a variable must be initialized to the default value, or is to be customized by a user, it must be declared here. The declaration can be used in two ways. One is to introduce a new variable. In that case, `VALUE` must not be omitted. Another is to inherit the variable from what declared in "global.mim", and to give the different default value and/or to make the variable customizable specially for the current input method. In the latter case, `VALUE` can be omitted.

`COMMAND-DECLARATION` declares a command used in this input method. If a command must be bound to the default key sequence, or is to be customized by a user, it must be declared here. Like `VARIABLE-DECLARATION`, the declaration can be used in two ways. One is to introduce a new command. In that case, `KEYSEQ` must not be omitted. Another is to inherit the command from what declared in "global.mim", and to give the different key binding and/or to make the command customizable specially for the current input method. In the latter case, `KEYSEQ` can be omitted.

    MODULE-LIST ::= '(' 'module' MODULE * ')'

    MODULE ::= '(' MODULE-NAME FUNCTION * ')'

    MODULE-NAME ::= SYMBOL

    FUNCTION ::= SYMBOL

Each `MODULE` declares the name of an external module (i.e. dynamic library) and function names exported by the module. If a `FUNCTION` has name "init", it is called with only the default arguments (see the section about `CALL`) when an input context is created for the input method. If a `FUNCTION` has name "fini", it is called with only the default arguments when an input context is destroyed.

    MACRO-LIST ::=  MACRO-INCLUSION ? '(' 'macro' MACRO * ')' MACRO-INCLUSION ?

    MACRO ::= '(' MACRO-NAME MACRO-ACTION * ')'

    MACRO-NAME ::= SYMBOL

    MACRO-ACTION ::= ACTION

    TAGS ::= `(` LANGUAGE NAME EXTRA-ID ? `)`

    MACRO-INCLUSION ::= '(' 'include' TAGS 'macro' MACRO-NAME ? ')'

`MACRO-INCLUSION` includes macros from another input method specified by `TAGS`. When `MACRO-NAME` is not given, all macros from the input method are included.

    MAP-LIST ::= MAP-INCLUSION ? '(' 'map' MAP * ')'
    MAP-INCLUSION ?

    MAP ::= '(' MAP-NAME RULE * ')'

    MAP-NAME ::= SYMBOL

    RULE ::= '(' KEYSEQ MAP-ACTION * ')'

    KEYSEQ ::= MTEXT | '(' [ SYMBOL | INTEGER ] * ')'

    MAP-INCLUSION ::= '(' 'include' TAGS 'map' MAP-NAME ? ')'

When an input method is never standalone and always included in another method, `MAP-LIST` can be omitted.

`SYMBOL` in the definitions of `MAP-NAME` must not be `t` nor `nil`.

`MTEXT` in the definition of `KEYSEQ` consists of characters that can be generated by a keyboard. Therefore `MTEXT` usually contains only ASCII characters. However, if the input method is intended to be used, for instance, with a West European keyboard, `MTEXT` may contain Latin-1 characters.

`SYMBOL` in the definition of `KEYSEQ` must be the return value of the minput_event_to_key() function. Under the X window system, you can quickly check the value using the `xev` command. For example, the return key, the backspace key, and the 0 key on the keypad are represented as ``(Return) , ``(BackSpace) , and ``(KP_0) respectively. If the shift, control, meta, alt, super, and hyper modifiers are used, they are represented by the S- , C- , M- , A- , s- , and H- prefixes respectively in this order. Thus, "return with shift with meta with hyper" is ``(S-M-H-Return) . Note that "a with shift" .. "z with shift" are represented simply as A .. Z . Thus "a with shift with meta with hyper" is ``(M-H-A) .

`INTEGER` in the definition of `KEYSEQ` must be a valid character code.

`MAP-INCLUSION` includes maps from another input method specified by `TAGS`. When `MAP-NAME` is not given, all maps from the input method are included.

    MAP-ACTION ::= ACTION

    ACTION ::= INSERT | DELETE | SELECT | MOVE | MARK
               | SHOW | HIDE | PUSHBACK | POP | UNDO
    	   | COMMIT | UNHANDLE | SHIFT | CALL
    	   | SET | IF | COND | '(' MACRO-NAME ')'

    PREDEFINED-SYMBOL ::=
        '@0' | '@1' | '@2' | '@3' | '@4'
        | '@5' | '@6' | '@7' | '@8' | '@9'
        | '@<' | '@=' | '@>' | '@-' | '@+' | '@[' | '@]'
        | '@@'
        | '@-0' | '@-N' | '@+N'

    STATE-LIST ::= STATE-INCUSION ? '(' 'state' STATE * ')'  STATE-INCUSION ?

    STATE ::= '(' STATE-NAME [ STATE-TITLE-TEXT ] BRANCH * ')'

    STATE-NAME ::= SYMBOL

    STATE-TITLE-TEXT ::= MTEXT

    BRANCH ::= '(' MAP-NAME BRANCH-ACTION * ')'
    	   | '(' 'nil' BRANCH-ACTION * ')'
    	   | '(' 't' BRANCH-ACTION * ')'

    STATE-INCLUSION ::= '(' 'include' TAGS 'state' STATE-NAME ? ')'

When an input system is never standalone and always included in another system, `STATE-LIST` can be omitted.

`STATE-INCLUSION` includes states from another input method specified by `TAGS`. When `STATE-NAME` is not given, all states from the input method are included.

The optional `STATE-TITLE-TEXT` specifies a title text displayed on the screen when the input method is in this state. If `STATE-TITLE-TEXT` is omitted, `TITLE-TEXT` is used.

In the first form of `BRANCH`, `MAP-NAME` must be an item that appears in `MAP`. In this case, if a key sequence matching one of `KEYSEQs` of `MAP-NAME` is typed, `BRANCH-ACTIONs` are executed.

In the second form of `BRANCH`, `BRANCH-ACTIONs` are executed if a key sequence that doesn't match any of `Branch's` of the current state is typed.

If there is no `BRANCH` beginning with `nil` and the typed key sequence does not match any of the current `BRANCHs`, the input method transits to the initial state.

In the third form of `BRANCH`, `BRANCH-ACTIONs` are executed when shifted to the current state. If the current state is the initial state, `BRANCH-ACTIONs` are executed also when an input context of the input method is created.

    BRANCH-ACTION ::= ACTION

An input method has the following two lists of symbols.

- marker list

  A marker is a symbol indicating a character position in the preediting text. The `MARK` action assigns a position to a marker. The position of a marker is referred by the `MOVE` and the `DELETE` actions.

- variable list

  A variable is a symbol associated with an integer, a symbol, or an M-text value. The integer value of a variable can be set and referred by the `SET` action. It can be referred by the `SET`, the `INSERT`, the `SELECT`, the `UNDO`, the `IF`, the `COND` actions. The M-text value of a variable can be referred by the `INSERT` action. The symbol value of a variable can not be referred directly, is used the library implicitly (e.g. candidates-charset). All variables are implicitly initialized to the integer value zero.

Each `PREDEFINED-SYMBOL` has a special meaning when used as a marker.

- `@0`, `@1`, `@2`, `@3`, `@4`, `@5`, `@6`, `@7`, `@8`, `@9`

  The 0th, 1st, 2nd, ... 9th position respectively.

- `@<`, `@=`, `@>`

  The first, the current, and the last position.

- `@-`, `@+`

  The previous and the next position.

- `@`[, `@`]

  The previous and the next position where a candidate list changes.

Some of the `PREDEFINED-SYMBOL` has a special meaning when used as a candidate index in the `SELECT` action.

- `@<`, `@=`, `@>`

  The first, the current, and the last candidate of the current candidate group.

- `@-`

  The previous candidate. If the current candidate is the first one in the current candidate group, then it means the last candidate in the previous candidate group.

- `@+`

  The next candidate. If the current candidate is the last one in the current candidate group, then it means the first candidate in the next candidate group.

- `@`[, `@`]

  The candidate in the previous and the next candidate group having the same candidate index as the current one.

And, this also has a special meaning.

- `@@`

  Number of handled keys at that moment.

These are for supporting surround text handling.

- `@-0`

  -1 if surrounding text is supported, -2 if not.

- `@-N`

  Here, `N` is a positive integer. The value is the Nth previous character in the preedit buffer. If there are only M (M<N) previous characters in it, the value is the (N-M)th previous character from the inputting spot. When this is used as the argument of `delete` action, it specifies the number of characters to be deleted.

- `@+N`

  Here, `N` is a positive integer. The value is the Nth following character in the preedit buffer. If there are only M (M<N) following characters in it, the value is the (N-M)th following character from the inputting spot. When this is used as the argument of `delete` action, it specifies the number of characters to be deleted.

The arguments and the behavior of each action are listed below.

    INSERT ::= '(' 'insert' MTEXT ')'
               | MTEXT
    	   | INTEGER
    	   | SYMBOL
               | '(' 'insert' SYMBOL ')'
               | '(' 'insert' '(' CANDIDATES * ')' ')'
               | '(' CANDIDATES * ')'

    CANDIDATES ::= MTEXT | '(' MTEXT * ')'

The first and second forms insert `MTEXT` before the current position.

The third form inserts the character `INTEGER` before the current position.

The fourth and fith form treats `SYMBOL` as a variable, and inserts its value (if it is a valid character code) before the current position.

In the sixth and seventh forms, each `CANDIDATES` represents a candidate group, and each element of `CANDIDATES` represents a candidate, i.e. if `CANDIDATES` is an M-text, the candidates are the characters in the M-text; if `CANDIDATES` is a list of M-texts, the candidates are the M-texts in the list.

These forms insert the first candidate before the current position. The inserted string is associated with the list of candidates and the information indicating the currently selected candidate.

The marker positions affected by the insertion are automatically relocated.

    DELETE ::= '(' 'delete' SYMBOL ')'
               | '(' 'delete' INTEGER ')'

The first form treats `SYMBOL` as a marker, and deletes characters between the current position and the marker position.

The second form treats `INTEGER` as a character position, and deletes characters between the current position and the character position.

The marker positions affected by the deletion are automatically relocated.

    SELECT ::= '(' 'select' PREDEFINED-SYMBOL ')'
               | '(' 'select' INTEGER ')'
    	   | '(' 'select' SYMBOL ')'

This action first checks if the character just before the current position belongs to a string that is associated with a candidate list. If it is, the action replaces that string with a candidate specified by the argument.

The first form treats `PREDEFINED-SYMBOL` as a candidate index (as described above) that specifies a new candidate in the candidate list.

The second form treats `INTEGER` as a candidate index that specifies a new candidate in the candidate list.

In the third form, `SYMBOL` must have a integer value, and it is treated as a candidate index.

    SHOW ::= '(show)'

This actions instructs the input method driver to display a candidate list associated with the string before the current position.

    HIDE ::= '(hide)'

This action instructs the input method driver to hide the currently displayed candidate list.

    MOVE ::= '(' 'move' SYMBOL ')'
             | '(' 'move' INTEGER ')'

The first form treats `SYMBOL` as a marker, and makes the marker position be the new current position.

The second form treats `INTEGER` as a character position, and makes that position be the new current position.

    MARK ::= '(' 'mark' SYMBOL ')'

This action treats `SYMBOL` as a marker, and sets its position to the current position. `SYMBOL` must not be a `PREDEFINED-SYMBOL`.

    PUSHBACK :: = '(' 'pushback' INTEGER ')'
                  | '(' 'pushback' KEYSEQ ')'

The first form pushes back the latest `INTEGER` number of key events to the event queue if `INTEGER` is positive, and pushes back all key events if `INTEGER` is zero.

The second form pushes back keys in `KEYSEQ` to the event queue.

    POP ::= '(' 'pop' ')'

This action pops the first key event that is not yet handled from the event queue.

    UNDO :: = '(' 'undo' [ INTEGER | SYMBOL ] ')'

If there's no argument, this action cancels the last two key events (i.e. the one that invoked this command, and the previous one).

If there's an integer argument NUM, it must be positive or negative (not zero). If positive, from the NUMth to the last events are canceled. If negative, the last (- NUM) events are canceled.

If there's a symbol argument, it must be resolved to an integer number and the number is treated as the actual argument as above.

    COMMIT :: = '(commit)'

This action commits the current preedit.

    UNHANDLE :: = '(unhandle)'

This action commits the current preedit and returns the last key as unhandled.

    SHIFT :: = '(' 'shift' STATE-NAME ')'

If `STATE-NAME` is `t`, this action shifts the current state to the previous one, otherwise it shifts to `STATE-NAME`. In the latter case, `STATE-NAME` must appear in `STATE-LIST`.

    CALL ::= '(' 'call' MODULE-NAME FUNCTION ARG * ')'

    ARG ::= INTEGER | SYMBOL | MTEXT | PLIST

This action calls the function `FUNCTION` of external module `MODULE-NAME`. `MODULE-NAME` and `FUNCTION` must appear in `MODULE-LIST`.

The function is called with an argument of the type (MPlist *). The key of the first element is Mt and its value is a pointer to an object of the type MInputContext. The key of the second element is Msymbol and its value is the current state name. `ARGs` are used as the value of the third and later elements. Their keys are determined automatically; if an `ARG` is an integer, the corresponding key is Minteger; if an `ARG` is a symbol, the corresponding key is Msymbol, etc.

The function must return NULL or a value of the type (MPlist *) that represents a list of actions to take.

    SET ::= '(' CMD SYMBOL1 EXPRESSION ')'

    CMD ::= 'set' | 'add' | 'sub' | 'mul' | 'div'

    EXPRESSION ::= INTEGER | SYMBOL2 | '(' OPERATOR EXPRESSION * ')'

    OPERATOR ::= '+' | '-' | '*' | '/' | '|' | '&' | '!'
                | '=' | '<' | '>' | '<=' | '>='

This action treats `SYMBOL1` and `SYMBOL2` as variables and sets the value of `SYMBOL1` as below.

If `CMD` is 'set', it sets the value of `SYMBOL1` to the value of `EXPRESSION`.

If `CMD` is 'add', it increments the value of `SYMBOL1` by the value of `EXPRESSION`.

If `CMD` is 'sub', it decrements the value of `SYMBOL1` by the value of `EXPRESSION`.

If `CMD` is 'mul', it multiplies the value of `SYMBOL1` by the value of `EXPRESSION`.

If `CMD` is 'div', it divides the value of `SYMBOL1` by the value of `EXPRESSION`.

    IF ::= '(' CONDITION ACTION-LIST1 ACTION-LIST2 ? ')'

    CONDITION ::= [ '=' | '<' | '>' | '<=' | '>=' ] EXPRESSION1 EXPRESSION2

    ACTION-LIST1 ::= '(' ACTION * ')'

    ACTION-LIST2 ::= '(' ACTION * ')'

This action performs actions in `ACTION-LIST1` if `CONDITION` is true, and performs `ACTION-LIST2` (if any) otherwise.

    COND ::= '(' 'cond' [ '(' EXPRESSION ACTION * ') ] * ')'

This action performs the first action `ACTION` whose corresponding `EXPRESSION` has nonzero value.

### EXAMPLE 1

This is a very simple example for inputting Latin characters with diacritical marks (acute and cedilla). For instance, when you type:

        Comme'die-Franc,aise, chic,,

you will get this:

The definition of the input method is very simple as below, and it is quite straight forward to extend it to cover all Latin characters.

### EXAMPLE 2

This example is for inputting Unicode characters by typing C-u (Control-u) followed by four hexadecimal digits. For instance, when you type ("^u" means Control-u):

        ^u2190^u2191^u2192^u2193

you will get this (Unicode arrow symbols):

The definition utilizes `SET` and `IF` commands as below:

    (title "UNICODE")
    (map
     (starter
      ((C-U) "U+"))
     (hex
      ("0" ?0) ("1" ?1) ... ("9" ?9) ("a" ?A) ("b" ?B) ... ("f" ?F)))
    (state
     (init
      (starter (set code 0) (set count 0) (shift unicode)))
     (unicode
      (hex (set this @-)
           (< this ?A
    	  ((sub this 48))
    	  ((sub this 55)))
           (mul code 16) (add code this)
           (add count 1)
           (= count 4
    	  ((delete @<) (insert code) (shift init))))))

### EXAMPLE 3

This example is for inputting Chinese characters by typing PinYin key sequence.

### SEE ALSO

Input Methods provided by the m17n database, mdbGeneral(5)