Reference for all built-in template language functions

Here, we document all the built-in functions available in the calibre template language. Every function is implemented as a class in python and you can click the source links to see the source code, in case the documentation is insufficient. The functions are arranged in logical groups by type.

GUI関数群

selected_books

class calibre.utils.formatter_functions.BuiltinSelectedBooks[ソース]

selected_books([sorted_by, ascending]) -- 現在選択されている本を、選択順に並べた本IDのリストを返します。 この関数はGUIでのみ使用可能です。

selected_column

class calibre.utils.formatter_functions.BuiltinSelectedColumn[ソース]

selected_column() -- 現在選択されているセルを含む列のルックアップ名を返します。セルが選択されていない場合は '' を返します。 この関数はGUIでのみ使用できます。

show_dialog

class calibre.utils.formatter_functions.BuiltinShowDialog[ソース]

show_dialog(html_or_text) -- HTMLまたはテキストを含むダイアログを表示します。ユーザーがOKボタンを押すと関数は '1'``を返し、キャンセルボタンを押すと ``'' を返します。 この関数はGUI環境でのみ使用できます。

sort_book_ids

class calibre.utils.formatter_functions.BuiltinSortBookIds[ソース]

sort_book_ids(book_ids, sorted_by, ascending [, sorted_by, ascending]*) -- sorted_by で指定されたルックアップ名で指定された列で、ascending で指定された順序でソートされた本ID のリストを返します。ascending'1' の場合、本は 'sorted_by' 列の値で昇順にソートされ、それ以外の場合は降順にソートされます。sorted_by, ascending のペアは複数指定できます。最初のペアは主要な順序を指定します。この関数は GUI でのみ使用できます。

width_from_pages

class calibre.utils.formatter_functions.BuiltinWidthFromPages[ソース]

width_from_pages(value [, num_of_pages_for_max_width, logarithmic_factor, default_width]) -- ページ数を指定して、本の背表紙の幅を '0' から '1' の間の分数で返します。これは、本棚ビューでページ数から背表紙の幅を計算するために使用されます。オプションの引数は、幅の計算方法を制御します。

  • num_of_pages_for_max_width -- 最も幅の広い本を制御します。指定されたページ数以上の本には幅 1 が与えられます。デフォルトは 1500 です。

  • logarithmic_factor -- ページ数が 0 から最大ページ数まで変化したときに、幅がどのくらいの速さで変化するかを制御します。デフォルトは 2 です。

  • default_width -- ページ数が無効な本の幅です。

URL関数

encode_for_url

class calibre.utils.formatter_functions.BuiltinEncodeForURL[ソース]

encode_for_url(value, use_plus) -- use_plus``で指定された方法で、URLで使用できるように``value``をエンコードして返します。最初に、値はURLエンコードされます。次に、``use_plus0 の場合は、スペースが '+' (プラス記号) に置き換えられます。use_plus1 の場合は、スペースが %20 に置き換えられます。

値自体をエンコードせずにスペースのみを置き換えたい場合は、re($series, ' ', '%20') のように re() 関数を使用してください。 関数として make_url()make_url_extended() または query_string() も参照してください。

make_url

class calibre.utils.formatter_functions.BuiltinMakeUrl[ソース]

make_url(path, [query_name, query_value]+) -- この関数は、クエリURLを構築する最も簡単な方法です。クエリ対象のWebサイトとページを示す path と、クエリ構築に使用される query_namequery_value のペアを使用します。一般的に、 query_value はURLエンコードされている必要があります。この関数では、常にエンコードされ、スペースは常に``'+'``に置き換えられます。

少なくとも1つの query_name、query_value ペアを指定する必要があります。

例:著者「Niccolò Machiavelli」のWikipedia検索URLを作成する場合:

make_url('https://en.wikipedia.org/w/index.php', 'search', 'Niccolò Machiavelli')

結果:

https://en.wikipedia.org/w/index.php?search=Niccol%C3%B2+Machiavelli

カスタム列の書籍詳細URLテンプレートを作成する場合は、クリックされたフィールドの値を取得するために、$item_name または field('item_name') を使用してください。例:`Niccolò Machiavelli`がクリックされた場合、以下のコードを使用してURLを構築できます。

make_url('https://en.wikipedia.org/w/index.php', 'search', $item_name)

make_url_extended()query_string()encode_for_url() 関数も参照してください。

make_url_extended

class calibre.utils.formatter_functions.BuiltinMakeUrlExtended[ソース]

make_url_extended(...) -- この関数は make_url() と似ていますが、URL の構成要素をより細かく制御できます。URL の構成要素は

scheme:://authority/path?query string です。

詳細は、Wikipedia の Uniform Resource Locator を参照してください。

この関数には次の2つのバリエーションがあります。

make_url_extended(scheme, authority, path, [query_name, query_value]+)

および

make_url_extended(scheme, authority, path, query_string)

この関数は、 schemeauthoritypath 、および query_string 、またはクエリ引数のペアから構築されたクエリ文字列から構成されるURLを返します。 authority は空にすることができます。これは calibre スキームのURLの場合に該当します。 query_string 、または少なくとも1つの query_name, query_value ペアを指定する必要があります。 query_string を指定し、それが空の場合、生成されるURLにはクエリ文字列セクションは含まれません。

例1:著者`Niccolò Machiavelli`のWikipedia検索URLを作成する:

make_url_extended('https', 'en.wikipedia.org', '/w/index.php', 'search', 'Niccolò Machiavelli')

結果:

https://en.wikipedia.org/w/index.php?search=Niccol%C3%B2+Machiavelli

make_url_extended()query_string を使用した例については、:ref:`query_string() <ff_query_string>`関数を参照してください。

カスタム列の書籍詳細URLテンプレートを作成する場合は、クリックされたフィールドの値を取得するために $item_name または field('item_name') を使用してください。例:`Niccolò Machiavelli`がクリックされた場合、以下のコードを使用してURLを構築できます。

make_url_extended('https', 'en.wikipedia.org', '/w/index.php', 'search', $item_name')

make_url()query_string()、:ref:`encode_for_url() <ff_encode_for_url>`関数も参照してください。

query_string

class calibre.utils.formatter_functions.BuiltinQueryString[ソース]

query_string([query_name, query_value, how_to_encode]+)-- returns a URL query string constructed from the query_name, query_value, how_to_encode triads. A query string is a series of items where each item looks like query_name=query_value where query_value is URL-encoded as instructed. The query items are separated by '&' (ampersand) characters.

If how_to_encode is 0 then query_value is encoded and spaces are replaced with '+' (plus) signs. If how_to_encode is 1 then query_value is encoded with spaces replaced by %20. If how_to_encode is 2 then query_value is returned unchanged; no encoding is done and spaces are not replaced. If you want query_value not to be encoded but spaces to be replaced then use the re() function, as in re($series, ' ', '%20')

You use this function if you need specific control over how the parts of the query string are constructed. You could then use the resultingquery string in make_url_extended(), as in

make_url_extended(
       'https', 'your_host', 'your_path',
       query_string('encoded', 'Hendrik Bäßler', 0, 'unencoded', 'Hendrik Bäßler', 2))

giving you

https://your_host/your_path?encoded=Hendrik+B%C3%A4%C3%9Fler&unencoded=Hendrik Bäßler

You must have at least one query_name, query_value, how_to_encode triad, but can have as many as you wish.

The returned value is a URL query string with all the specified items, for example: name1=val1[&nameN=valN]*. Note that the '?' path / query string separator is not included in the returned result.

If you are writing a custom column book details URL template then use $item_name or field('item_name') to obtain the unencoded value of the field that was clicked. You also have item_value_quoted where the value is already encoded with plus signs replacing spaces, and item_value_no_plus where the value is already encoded with %20 replacing spaces.

See also the functions make_url(), make_url_extended() and encode_for_url().

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "`" for italics on line 21 in "query_string"

to_hex

class calibre.utils.formatter_functions.BuiltinToHex[ソース]

to_hex(val) -- 文字列 val を 16 進数にエンコードして返します。 これは、calibre URL を構築する際に便利です。

urls_from_identifiers

class calibre.utils.formatter_functions.BuiltinUrlsFromIdentifiers[ソース]

urls_from_identifiers(identifiers, sort_results) -- カンマ区切りの identifiers のリストが与えられると、identifier はコロン区切りの値のペア (id_name:id_value) で、識別子から生成された HTML URL のカンマ区切りのリストが返されます。 sort_results0 (文字または数値) の場合はリストはソートされませんが、それ以外の場合は識別子名でアルファベット順にソートされます。URL は、書籍の詳細に表示される組み込みの識別子列と同じ方法で生成されます。

その他の文字

arguments

class calibre.utils.formatter_functions.BuiltinArguments[ソース]

arguments(id[=expression] [, id[=expression]]*) -- 保存済みテンプレートで使用され、呼び出しで渡された引数を取得します。 指定された名前、id でローカル変数を宣言および初期化し、実質的にパラメータにします。変数は位置指定型です。呼び出しで指定された引数の値が、同じ位置に格納されます。対応する引数が呼び出しで指定されていない場合、arguments() はその変数に指定されたデフォルト値を割り当てます。デフォルト値がない場合は、変数は空の文字列に設定されます。

assign

class calibre.utils.formatter_functions.BuiltinAssign[ソース]

assign(id, value) -- id``に ``value を代入し、 `value を返します。id は識別子である必要があり、式であってはなりません。ほとんどの場合、この関数の代わりに = 演算子を使用できます。

globals

class calibre.utils.formatter_functions.BuiltinGlobals[ソース]

globals(id[=expression] [, id[=expression]]*) -- フォーマッタに渡せる "グローバル変数" を取得します。 id はグローバル変数の名前です。id パラメータで渡されたグローバル変数の名前を使用して、ローカル変数を宣言および初期化します。対応する変数が globals で指定されていない場合は、その変数に指定されたデフォルト値を割り当てます。デフォルト値がない場合は、変数は空の文字列に設定されます。

is_dark_mode

class calibre.utils.formatter_functions.BuiltinIsDarkMode[ソース]

is_dark_mode() -- calibreがダークモードで実行されている場合は '1' を、それ以外の場合は '' (空文字列)を返します。 この関数は、高度な色とアイコンのルールで使用することで、モードに応じて異なる色やアイコンを選択できます。例:

if is_dark_mode() then 'dark.png' else 'light.png' fi

print

class calibre.utils.formatter_functions.BuiltinPrint[ソース]

print(a [, b]*) -- 引数を標準出力に出力します。 コマンドラインからcalibreを起動しない限り(calibre-debug -g``を使用しない限り)、出力はどこにも表示されません。``print 関数は常に最初の引数を返します。

set_globals

class calibre.utils.formatter_functions.BuiltinSetGlobals[ソース]

set_globals(id[=expression] [, id[=expression]]*) -- フォーマッタに渡せるグローバル変数を設定します。 グローバル変数には、渡された id の名前が付けられます。式が指定されていない限り、id の値が使用されます。

ケースの変更

capitalize

class calibre.utils.formatter_functions.BuiltinCapitalize[ソース]

capitalize(value) -- 指定された value の最初の文字を大文字に、それ以外の文字を小文字にして返します。

lowercase

class calibre.utils.formatter_functions.BuiltinLowercase[ソース]

lowercase(value) -- 指定された value を小文字に変換して返します。

titlecase

class calibre.utils.formatter_functions.BuiltinTitlecase[ソース]

titlecase(value) -- value をタイトルケースで返します。

uppercase

class calibre.utils.formatter_functions.BuiltinUppercase[ソース]

uppercase(value) -- value を大文字で返します。

データベース関数

annotation_count

class calibre.utils.formatter_functions.BuiltinAnnotationCount[ソース]

annotation_count() -- 現在の本に添付されているすべてのタイプの注釈の合計数を返します。 この関数は、GUI とコンテンツ サーバーでのみ動作します。

approximate_formats

class calibre.utils.formatter_functions.BuiltinApproximateFormats[ソース]

approximate_formats() -- 書籍に関連付けられた形式をカンマ区切りのリストで返します。このリストはファイルシステムではなくcalibreのデータベースから取得されるため、正確である保証はありませんが、おそらく正しいでしょう。なお、返されるフォーマット名は常にEPUBのように大文字になります。approximate_formats() 関数は、 formats_... 関数よりもはるかに高速です。この関数はGUIでのみ動作します。これらの値をディスクへの保存またはデバイスへの送信テンプレートで使用したい場合は、カスタムの``他の列から構築された列``を作成し、その列のテンプレートでこの関数を使用し、保存/送信テンプレートでその列の値を使用する必要があります。

book_count

class calibre.utils.formatter_functions.BuiltinBookCount[ソース]

book_count(query, use_vl) -- query を検索して見つかった書籍の数を返します。 use_vl0 (ゼロ) の場合、仮想ライブラリは無視されます。この関数と対応する book_values() は、テンプレート検索で特に役立ちます。1冊の本のみを含むシリーズを検索するなど、複数の本の情報を組み合わせた検索をサポートします。Tweak allow_template_database_functions_in_composites が True に設定されていない限り、複合列では使用できません。GUI でのみ使用できます。

例えば、次のテンプレート検索では、この関数と対応する関数を使用して、1冊の本のみを含むシリーズをすべて検索します。

  • series_only_one_book (名前は任意) という保存済みテンプレートを定義します (環境設定  →  高度な設定  →  テンプレート関数 を使用)。テンプレートは次のとおりです。

    program:
      vals = globals(vals='');
      if !vals then
        all_series = book_values('series', 'series:true', ',', 0);
        for series in all_series:
          if book_count('series:="' & series & '"', 0) == 1 then
            vals = list_join(',', vals, ',', series, ',')
          fi
        rof;
        set_globals(vals)
      fi;
      str_in_list(vals, ',', $series, 1, '')
    

    テンプレートが初めて実行される際(最初にチェックされる本)、データベース検索の結果を global テンプレート変数 vals に保存します。これらの結果は、検索をやり直すことなく、後続の本をチェックするために使用されます。

  • テンプレート検索で保存済みテンプレートを使用する:

template:"program: series_only_one_book()#@#:n:1"

検索にテンプレートを入力する代わりに保存済みテンプレートを使用すると、検索式で引用符をエスケープする必要があることに起因する問題を回避できます。

この機能はGUIとコンテンツサーバーでのみ使用できます。

book_values

class calibre.utils.formatter_functions.BuiltinBookValues[ソース]

book_values(column, query, sep, use_vl) -- query で検索された本の列 column (ルックアップ名) に含まれる一意の値を sep で区切ったリストを返します。 use_vl0 (ゼロ) の場合、仮想ライブラリは無視されます。この関数と対応する book_count() は、テンプレート検索で特に役立ちます。1冊の本のみを含むシリーズを検索するなど、多数の本の情報を組み合わせた検索をサポートします。Tweak allow_template_database_functions_in_composites が True に設定されていない限り、複合列では使用できません。この関数はGUIとコンテンツサーバーでのみ使用できます。

extra_file_modtime

class calibre.utils.formatter_functions.BuiltinExtraFileModtime[ソース]

extra_file_modtime(file_name, format_string) -- 本の data/ フォルダーにある追加ファイル``file_name`` の最終更新日時を返します。 ファイルが存在しない場合は`-1`を返します。更新日時は format_string に従ってフォーマットされます(詳細は format_date() を参照)。 format_string が空文字列の場合は、エポックからの経過秒数を浮動小数点数で返します。 関数 has_extra_files()extra_file_names() 、または extra_file_size() も参照してください。エポックはOSによって異なります。この関数はGUIおよびコンテンツサーバーでのみ使用できます。

extra_file_names

class calibre.utils.formatter_functions.BuiltinExtraFileNames[ソース]

extra_file_names(sep [, pattern]) -- returns a sep-separated list of extra files in the book's data/ folder. If the optional parameter pattern, a regular expression, is supplied then the list is filtered to files that match pattern. The pattern match is case insensitive. See also the functions has_extra_files(), extra_file_modtime() and extra_file_size(). This function can be used only in the GUI and the content server.

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "``" for CODE_TEXT on line 3 in "extra_file_names"

extra_file_size

class calibre.utils.formatter_functions.BuiltinExtraFileSize[ソース]

extra_file_size(file_name) -- 本の data/ フォルダにある追加ファイル file_name のサイズをバイト単位で返します。ファイルが存在しない場合は`-1`を返します。 関数 has_extra_files()extra_file_names() 、または extra_file_modtime() も参照してください。この関数はGUIおよびコンテンツサーバーでのみ使用できます。

formats_modtimes

class calibre.utils.formatter_functions.BuiltinFormatsModtimes[ソース]

formats_modtimes(date_format_string) -- 本の各形式の更新日時を表す、コロンで区切られた項目``FMT:DATE`` をカンマ区切りで並べたリストを返します。date_format_string パラメータは、日付の表示フォーマットを指定します。詳細について、 format_date() 関数を参照してください。特定のフォーマットの更新日時を取得するには、select() 関数を使用できます。フォーマット名はEPUBのように常に大文字であることに注意してください。

formats_path_segments

class calibre.utils.formatter_functions.BuiltinFormatsPathSegments[ソース]

formats_path_segments(with_author, with_title, with_format, with_ext, sep) -- calibreライブラリ内の本のフォーマットへのパスの一部を sep で区切って返します。 パラメータ sep は通常、スラッシュ ('/') です。このパラメータの用途の一つは、「ディスクに保存」および「デバイスに送信」テンプレートで生成されるパスが一貫して短縮されるようにすることです。また、デバイス上のパスが calibreライブラリ内のパスと一致するようにするためでもあります。

本のパスは、著者、括弧で囲まれた calibre データベースID を含むタイトル、およびフォーマット (著者 - タイトル) の3つのセグメントで構成されます。calibreはファイル名の長さ制限により、これら3つのセグメントのいずれかを短縮することができます。含めるセグメントを選択するには、そのセグメントに 1 を渡します。セグメントが不要な場合は、そのセグメントに 0 または空文字列を渡します。例えば、以下のコードは拡張子を除いたフォーマット名のみを返します。

formats_path_segments(0, 0, 1, 0, '/')

セグメントは1つしかないため、区切り文字は無視されます。

複数のフォーマット(複数の拡張子)がある場合は、拡張子の1つがランダムに選択されます。どの拡張子を使用するかを指定したい場合は、拡張子を除いたパスを取得し、それに希望する拡張子を追加してください。

例: calibre ライブラリに、Joe Blogs 著の「Help」というタイトルの epub 形式の書籍があるとします。パスは次のようになります。

Joe Blogs/Help - (calibre_id)/Help - Joe Blogs.epub

以下は、各パラメータに対して返される値です。

  • formats_path_segments(0, 0, 1, 0, '/')Help - Joe Blogs を返します。

  • formats_path_segments(0, 0, 1, 1, '/')Help - Joe Blogs.epub を返します。

  • formats_path_segments(1, 0, 1, 1, '/')Joe Blogs/Help - Joe Blogs.epub を返します。

  • formats_path_segments(1, 0, 1, 0, '/')Joe Blogs/Help - Joe Blogs を返します。

  • formats_path_segments(0, 1, 0, 0, '/')Help - (calibre_id) を返します

formats_paths

class calibre.utils.formatter_functions.BuiltinFormatsPaths[ソース]

formats_paths([separator]) -- 本の形式へのフルパスを示す FMT:PATH 項目を、指定された``separator`` で区切ったリストを返します。 separator 引数はオプションです。指定しない場合は、区切り文字は ', '``(カンマ+スペース)になります。区切り文字がカンマの場合は、 ``select() 関数を使用して特定の形式のパスを取得できます。形式名はEPUBのように常に大文字であることに注意してください。

formats_sizes

class calibre.utils.formatter_functions.BuiltinFormatsSizes[ソース]

formats_sizes() -- 本の各形式のサイズをバイト単位で示す、コロンで区切られた FMT:SIZE 項目をカンマ区切りで並べたリストを返します。 特定の形式のサイズを取得するには、select() 関数を使用できます。フォーマット名はEPUBのようには常に大文字であることに注意してください。

get_note

class calibre.utils.formatter_functions.BuiltinGetNote[ソース]

get_note(field_name, field_value, plain_text) -- fetch the note for field field_name with value field_value. If plain_text is empty, return the note's HTML including images. If plain_text is 1 (or '1'), return the note's plain text. If the note doesn't exist, return the empty string in both cases. Example:

  • Return the HTML of the note attached to the tag Fiction:

    program:
        get_note('tags', 'Fiction', '')
    
  • Return the plain text of the note attached to the author Isaac Asimov:

    program:
        get_note('authors', 'Isaac Asimov', 1)
    

This function works only in the GUI and the content server.

FFML エラーのため、ドキュメントを英語で表示します。 Missing [*] in list near text:" [*]タグ `Fi" on line 5 in "get_note"

has_extra_files

class calibre.utils.formatter_functions.BuiltinHasExtraFiles[ソース]

has_extra_files([pattern]) -- エクストラファイルの個数を返します。指定しない場合は空の文字列を返します。 オプションのパラメーター pattern (正規表現) が指定されている場合、リストは pattern に一致するファイルにフィルタリングされてから個数がカウントされます。パターンの一致は大文字と小文字を区別しません。関数 extra_file_names()extra_file_size()、および extra_file_modtime() も参照してください。この関数は GUI およびコンテンツ サーバーでのみ使用できます。

has_note

class calibre.utils.formatter_functions.BuiltinHasNote[ソース]

has_note(field_name, field_value) -- フィールドにノートが付いているかどうかを確認します。 この関数には2つのバリエーションがあります。

  • field_value が空文字列 ('') でない場合、フィールド field_name の値 field_value にノートが付いている場合は '1' を返し、それ以外の場合は '' を返します。

例: has_note('tags', 'Fiction') は、タグ fiction にノートが付いている場合は '1' を返し、それ以外の場合は '' を返します。

  • field_value が空文字列 ('') の場合、field_name フィールド内でノートが付いている値のリストを返します。フィールド内のどの項目にもノートが付いていない場合は '' を返します。このバリエーションは、特定の値ではなく、フィールド内のいずれかの値にノートが付いている場合に列アイコンを表示するのに便利です。

例: has_note('authors', '') は、ノートが付いている著者のリストを返します。どの著者にもノートが付いていない場合は '' を返します。

field_name フィールド内のすべての値にノートが付いているかどうかは、この関数の戻り値のリストの長さと field_name フィールドの値のリストの長さを比較することで確認できます。 例:

list_count(has_note('authors', ''), '&') ==# list_count_field('authors')

この関数は、GUIおよびコンテンツサーバーでのみ動作します。

reading_progress

class calibre.utils.formatter_functions.BuiltinReadingProgress[ソース]

reading_progress(book_id, [user, output_fmt, which, fmt]) -- 指定された出力形式で読書進捗状況を返します。 user パラメータは、デフォルトではすべてのユーザーに対応します。calibre電子書籍ビューアの読書進捗状況に対応するには、local を使用します。コンテンツサーバービューアの匿名ユーザーの読書進捗状況に対応するには、_ を使用します。その他の値は、コンテンツサーバーで使用されている対応するユーザー名に対応します。

output_fmt パラメータは、この関数が返すテキストの形式を制御します。以下のいずれかの値を指定できます。

  • page_count - デフォルト。読了ページ数 / 総ページ数 を出力します。ページカウントが有効になっていない場合は、代わりに読了率を出力します。

  • percent - 読了率を出力します。

  • percent_number - 読了率を末尾のパーセント記号なしの数値で出力します。ソートに便利です。

  • pos_frac - 0から1までの小数値を出力します。

which パラメータは、指定された user の読書進捗状況レコードの選択方法を制御します。ユーザーが指定されていない場合、または本が複数のフォーマットや複数のデバイスで読まれている場合は、複数のレコードが存在する可能性があります。このパラメータには、以下の2つの値を指定できます。

  • most_recent - 本を最後に読んだユーザーの進捗状況(デフォルト値)

  • furthest - 一致するすべてのレコードの中で最も進んだ進捗状況

fmt パラメータは、使用する本のフォーマットを制御します。デフォルトではすべてのフォーマットのレコードが返され、特定のレコードは which パラメータによって選択されます。

例:

{id:reading_progress()} -- この本を最近読んだ際の読書進捗状況(読んだページ数/総ページ数)
{id:reading_progress(,percent)} -- 上記と同様ですが、パーセンテージで表します。
{id:reading_progress(,pos_frac,furthest)} -- 上記と同様ですが、分数で表し、この本の最も進んだ読書進捗状況を使用します。
{id:reading_progress(bob,pos_frac,furthest,EPUB)} -- ユーザー「bob」と「EPUB」形式の場合。

ブール値

and

class calibre.utils.formatter_functions.BuiltinAnd[ソース]

and(value [, value]*) -- すべての値が空でない場合は文字列「'1'」を返し、それ以外の場合は空文字列を返します。値はいくつでも指定できます。ほとんどの場合、この関数の代わりに && 演算子を使用できます。 and()&& に置き換えない方が良い場合の一つは、短絡評価によって副作用が発生し、結果が変わる可能性がある場合です。例えば、 and(a='',b=5) は常に両方の代入を実行しますが、&& 演算子でこの場合は2番目の代入が実行されません。

not

class calibre.utils.formatter_functions.BuiltinNot[ソース]

not(value) -- 値が空の場合は文字列 '1'``を返し、それ以外の場合は空文字列を返します。 この関数は通常、単項否定演算子( ``! )で置き換えることができます。

or

class calibre.utils.formatter_functions.BuiltinOr[ソース]

or(value [, value]*) -- いずれかの値が空でない場合は文字列 '1' を返し、それ以外の場合は空の文字列を返します。 値はいくつでも指定できます。この関数は通常 || 演算子で置き換えることができます。置き換えることができない理由の 1 つは、短絡評価によって副作用のために結果が変わる場合です。

リストルックアップ

identifier_in_list

class calibre.utils.formatter_functions.BuiltinIdentifierInList[ソース]

identifier_in_list(val, id_name [, found_val, not_found_val]) -- val をカンマで区切られた識別子のリストとして扱います。識別子は id_name:value の形式です。id_name パラメータは検索対象の id_name テキストで、id_name または id_name:regexp のいずれかの形式です。前者の場合は、指定された id_name に一致する識別子がリスト内に存在すれば一致とみなされます。後者の場合は、id_name が識別子に一致し、かつ regexp がその識別子の値に一致すれば一致とみなされます。 found_val と```not_found_val`` が指定されている場合、一致すれば found_val を返し、一致しない場合は not_found_val を返します。 found_valnot_found_val が指定されていない場合、一致すれば identifier:value のペアを返し、一致しない場合は空文字列( '' )を返します。

list_contains

class calibre.utils.formatter_functions.BuiltinInList[ソース]

list_contains(value, separator, [ pattern, found_val, ]* not_found_val) -- valueseparator で区切られた項目のリストとして解釈し、リスト内の各項目に対して pattern をチェックします。 pattern が項目と一致する場合は found_val を返し、一致しない場合は not_found_val を返します。patternfound_value のペアは必要なだけ繰り返すことができ、項目の値に応じて異なる値を返すことができます。パターンは順番にチェックされ、最初に一致したものが返されます。

別名: in_list()、list_contains()

list_item

class calibre.utils.formatter_functions.BuiltinListitem[ソース]

list_item(value, index, separator) -- valueseparator で区切られた項目のリストとして解釈し、'index' 番目の項目を返します。 最初の項目は番号 0 です。最後の項目は、list_item(-1,separator) のように、インデックス -1 を持ちます。項目がリストに含まれていない場合は、空の文字列が返されます。separator は count 関数と同じ意味を持ち、通常はカンマ(,)ですが、著者のようなリストの場合はアンパサンド(&)です。

select

class calibre.utils.formatter_functions.BuiltinSelect[ソース]

select(value, key) -- value を、各項目が id:id_value の形式 (calibre identifier 形式) を持つカンマ区切りの項目のリストとして解釈します。 この関数は、id が key と等しい最初のペアを見つけ、対応する id_value を返します。一致する id がない場合は、空の文字列を返します。

str_in_list

class calibre.utils.formatter_functions.BuiltinStrInList[ソース]

str_in_list(value, separator, [ string, found_val, ]+ not_found_val) -- valueseparator で区切られた項目のリストとして解釈し、string をリスト内の各値と比較します。 string は正規表現ではありません。string がいずれかの項目と等しい場合 (大文字と小文字を区別しない)、対応する found_val を返します。stringseparator が含まれている場合、リストとしても扱われ、各サブ値がチェックされます。stringfound_value のペアは、必要に応じて何度でも繰り返すことができ、string の値に応じて異なる値を返すことができます。どの文字列も一致しない場合は、not_found_value が返されます。文字列は順番にチェックされます。最初に一致したものが返されます。

リスト操作

list_count

class calibre.utils.formatter_functions.BuiltinCount[ソース]

list_count(value, separator) -- interprets the value as a list of items separated by separator and returns the number of items in the list. Most lists use a comma as the separator, but authors uses an ampersand (&).

Examples: {tags:list_count(,)}, {authors:list_count(&)}.

Aliases: count(), list_count()

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "`" for italics on line 5 in "list_count"

list_count_field

class calibre.utils.formatter_functions.BuiltinFieldListCount[ソース]

list_count_field(lookup_name) -- 指定されたルックアップ名 lookup_name を持つフィールド内の項目の数を返します。 このフィールドは authorstags のように複数の値を保持できるフィールドである必要があります。そうでない場合、この関数はエラーを発生させます。この関数は、calibreのデータを文字列に変換することなく直接処理するため、 list_count() よりもはるかに高速です。 例: list_count_field('tags')

list_count_matching

class calibre.utils.formatter_functions.BuiltinListCountMatching[ソース]

list_count_matching(value, pattern, separator) -- valueseparator で区切られた項目のリストとして解釈し、正規表現 pattern に一致するリスト内の項目の数を返します。 エイリアス: list_count_matching(), count_matching()

list_difference

class calibre.utils.formatter_functions.BuiltinListDifference[ソース]

list_difference(list1, list2, separator) -- list1 から list2 に含まれるすべての項目を削除したリストを返します。 比較では大文字小文字は区別しません。list1list2 の項目は separator で区切られており、返されるリストの項目も同様に separator で区切られます。

list_equals

class calibre.utils.formatter_functions.BuiltinListEquals[ソース]

list_equals(list1, sep1, list2, sep2, yes_val, no_val) -- list1``と``list2``に同じ項目が含まれている場合は``yes_val``を返し、そうでない場合は``no_val``を返します。 項目は、適切な区切り文字(``sep1``または``sep2)を使用して各リストを分割することによって決定されます。リスト内の項目の順序は関係ありません。比較では大文字と小文字は区別されません。

list_intersection

class calibre.utils.formatter_functions.BuiltinListIntersection[ソース]

list_intersection(list1, list2, separator) -- list1 から list2 に存在しない項目を大文字小文字を区別しない比較で削除して作成したリストを返します。list1list2 の項目は separator で区切られ、返されるリストの項目も同様に separator で区切られます。

list_join

class calibre.utils.formatter_functions.BuiltinListJoin[ソース]

list_join(with_separator, list1, separator1 [, list2, separator2]*) -- ソースリスト ( list1 など)の項目を、結果リストの項目間に with_separator を使用して結合したリストを返します。各ソースリスト list[123...] の項目は、関連付けられた separator[123...] で区切られます。リストにはゼロ値を含めることができます。publisher のような単一値フィールド、つまり実質的に1項目のリストにすることもできます。重複は、大文字小文字を区別しない比較を使用して削除されます。項目は、ソースリストに表示されている順序で返されます。リストの項目が文字の大文字小文字のみが異なる場合は、最後の項目が使用されます。すべての区切り文字は、複数文字にすることができます。

例:

program:
list_join('#@#', $authors, '&', $tags, ',')

list_join は、以前に呼び出した list_join の結果に対して次のように使用できます。

program:
a = list_join('#@#', $authors, '&', $tags, ',');

b = list_join('#@#', a, '#@#', $#genre, ',', $#people, '&', 'some value', ',')

式を使用してリストを生成することもできます。たとえば、authors#genre の項目を取得したい場合、ジャンルを "Genre: " という単語の後にジャンルの頭文字を続けた形式に変更します。つまり、 "Fiction" というジャンルは "Genre: F" になります。以下でそれができます:

program:
    list_join('#@#', $authors, '&', list_re($#genre, ',', '^(.).*$', 'Genre: \1'),  ',')

list_re

class calibre.utils.formatter_functions.BuiltinListRe[ソース]

list_re(src_list, separator, include_re, opt_replace) -- src_listseparator 文字で区切ってリストを作成します。 リスト内の各項目について、include_re と一致するかどうかを確認します。一致する場合は、返されるリストに追加します。opt_replace が空文字列でない場合は、項目を返されるリストに追加する前に置換を適用します。

list_re_group

class calibre.utils.formatter_functions.BuiltinListReGroup[ソース]

list_re_group(src_list, separator, include_re, search_re [,template_for_group]*) -- list_re() と同様ですが、置換は省略できません。 置換を行う際には re_group(item, search_re, template ...) を使用します。

list_remove_duplicates

class calibre.utils.formatter_functions.BuiltinListRemoveDuplicates[ソース]

list_remove_duplicates(list, separator) -- list 内の重複する項目を削除して作成されたリストを返します。 項目が大文字小文字のみで異なる場合は、最後の項目が返されます。 list 内の項目は separator で区切られ、返されるリスト内の項目も同様に区切られます。

list_sort

class calibre.utils.formatter_functions.BuiltinListSort[ソース]

list_sort(value, direction, separator) -- 大文字小文字を区別しない字句ソートを使用してソートされた value を返します。 direction がゼロ (数値または文字) の場合、value は昇順でソートされ、それ以外の場合は降順でソートされます。リスト項目は separator で区切られ、返されるリストの項目も同様です。

list_split

class calibre.utils.formatter_functions.BuiltinListSplit[ソース]

list_split(list_val, sep, id_prefix) -- list_valsep を使用して複数の値に分割し、それぞれの値を id_prefix_N という名前のローカル変数に代入します。N はリスト内の値の位置です。最初の要素の位置は 0 (ゼロ) です。この関数はリストの最後の要素を返します。

例:

list_split('one:two:foo', ':', 'var')

は以下と同等です。

var_0 = 'one'

var_1 = 'two'

var_2 = 'foo'

list_union

class calibre.utils.formatter_functions.BuiltinListUnion[ソース]

list_union(list1, list2, separator) -- list1list2 の要素をマージしてリストを作成します。大文字小文字を区別しない比較で重複要素を削除します。要素の大文字小文字が異なる場合は、 list1 の要素が使用されます。 list1list2 の要素は separator で区切られ、返されるリストの要素も同様に``separator``で区切られます。

別名: merge_lists()list_union()

range

class calibre.utils.formatter_functions.BuiltinRange[ソース]

range(start, stop, step, limit) -- パラメータ startstop 、および step で指定された範囲をループして生成された数値のリストを返します。最大長は limit です。 最初に生成される値は 'start' です。以降の値は next_v = current_v + step です。ループは、 step が正の場合、 next_v < stop の間継続し、そうでない場合は next_v > stop の間継続します。start がテストに失敗した場合、つまり step が正の場合、 start >= stop の場合は、空のリストが生成されます。limit はリストの最大長を設定し、デフォルト値は 1000 です。パラメータ startstep、および limit は省略可能です。引数を 1 つ指定して range() を呼び出すと、stop が指定されます。引数を 2 つ指定すると、 startstop が指定されます。引数を 3 つ指定すると、 startstop 、および step が指定されます。 4つの引数で、 startstopsteplimit を指定します。

例:

range(5) -> '0, 1, 2, 3, 4'
range(0, 5) -> '0, 1, 2, 3, 4'
range(-1, 5) -> '-1, 0, 1, 2, 3, 4'
range(1, 5) -> '1, 2, 3, 4'
range(1, 5, 2) -> '1, 3'
range(1, 5, 2, 5) -> '1, 3'
range(1, 5, 2, 1) -> error(limit exceeded)

subitems

class calibre.utils.formatter_functions.BuiltinSubitems[ソース]

subitems(value, start_index, end_index) -- この関数は、ジャンルなどのタグのような階層構造を持つリストを分割します。 value は、カンマ区切りのタグのような項目のリストとして解釈され、各項目はピリオド区切りのリストです。各項目から start_index から end_index までの要素を抽出し、それらを結合して新しいリストを返します。重複する要素は削除されます。ピリオド区切りのリストの最初のサブ項目のインデックスはゼロです。インデックスが負の場合は、リストの末尾から数えます。特殊なケースとして、end_index がゼロの場合は、リストの長さとみなされます。

例:

  • #genre列に「A.B.C」が含まれている場合:

    • ``{#genre:subitems(0,1)}``は「A」を返します

    • ``{#genre:subitems(0,2)}``は「A.B」を返します

    • ``{#genre:subitems(1,0)}``は「B.C」を返します

  • #genre列に「A.B.C, D.E」が含まれている場合:

    • ``{#genre:subitems(0,1)}``は「A, D」を返します

    • ``{#genre:subitems(0,2)}``は「A.B, D.E」を返します

sublist

class calibre.utils.formatter_functions.BuiltinSublist[ソース]

sublist(value, start_index, end_index, separator) -- ``value``を``separator``で区切られた項目のリストとして解釈し、``start_index``から``end_index``までの項目から新しいリストを作成します。 最初の項目は0です。インデックスが負の場合は、リストの末尾から数えます。特殊なケースとして、end_indexが0の場合はリストの長さとみなされます。

タグ列(カンマ区切り)に「A, B, C」が含まれている場合の例:

  • ``{tags:sublist(0,1,,)}``は「A」を返します

  • ``{tags:sublist(-1,0,,)}``は「C」を返します

  • ``{tags:sublist(0,-1,,)}``は「A, B」を返します

リレーショナル

cmp

class calibre.utils.formatter_functions.BuiltinCmp[ソース]

cmp(value, y, lt, eq, gt) -- valuey``の両方を数値に変換してから比較します。  ``value <# y の場合は lt を、value ==# y の場合は eq を、それ以外の場合は gt を返します。この関数は通常、数値比較演算子( ==#<#># など)のいずれかに置き換えることができます。

first_matching_cmp

class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp[ソース]

first_matching_cmp(val, [ cmp, result, ]* else_result) -- val < cmp を順番に比較し、最初に条件を満たした比較に対応する result を返します。 どの比較も条件を満たさない場合は else_result を返します。

例:

i = 10;
first_matching_cmp(i,5,"small",10,"middle",15,"large","giant")

"large" を返します。最初の値を 16 にした場合、同じ例では "giant" が返されます。

strcmp

class calibre.utils.formatter_functions.BuiltinStrcmp[ソース]

strcmp(x, y, lt, eq, gt) -- xy の大文字小文字を区別しない字句比較を行います。 x < y の場合は ltx == y の場合は eq、それ以外の場合は gt を返します。この関数は、多くの場合、字句比較演算子( ==>< など)のいずれかに置き換えることができます。

strcmpcase

class calibre.utils.formatter_functions.BuiltinStrcmpcase[ソース]

strcmpcase(x, y, lt, eq, gt) -- xy の大文字小文字を区別する字句比較を行います。 x < y の場合は ltx == y の場合は eq 、それ以外の場合は gt を返します。

注:これは、例えば字句比較演算子( ==>< など)で使用されるcalibreのデフォルトの動作ではありません。この関数は予期しない結果を引き起こす可能性があるため、可能な限り strcmp() を使用することをお勧めします。

値の書式設定

f_string

class calibre.utils.formatter_functions.BuiltinFString[ソース]

f_string(string) -- interpret string similar to how python interprets f strings. The intended use is to simplify long sequences of str & str or strcat(a,b,c) expressions.

Text between braces ({ and }) must be General Program Mode template expressions. The expressions, which can be expression lists, are evaluated in the current context (current book and local variables). Text not between braces is passed through unchanged.

Examples:

  • f_string('Here is the title: {$title}') - returns the string with {$title} replaced with the title of the current book. For example, if the book's title is 20,000 Leagues Under the Sea then the f_string() returns Here is the title: 20,000 Leagues Under the Sea.

  • Assuming the current date is 18 Sept 2025, this f_string()

    f_string("Today's date: the {d = today(); format_date(d, 'd')} of {format_date(d, 'MMMM')}, {format_date(d, 'yyyy')}")
    

    returns the string Today's date: the 18 of September, 2025. Note the expression list (an assignment then an if statement) used in the first { ... } group to assign today's date to a local variable.

  • If the book is book #3 in a series named Foo that has 5 books then this template

    program:
        if $series then
            series_count = book_count('series:"""=' & $series & '"""', 0);
            return f_string("{$series}, book {$series_index} of {series_count}")
        fi;
        return 'This book is not in a series'
    

    returns Foo, book 3 of 5

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "`" for italics on line 22 in "f_string"

finish_formatting

class calibre.utils.formatter_functions.BuiltinFinishFormatting[ソース]

finish_formatting(value, format, prefix, suffix) -- {series_index:05.2f| - |- }``のようなテンプレートで行われるのと同様に、 ``formatprefixsuffixvalue に適用します。 この関数は、複雑な単一関数モードまたはテンプレートプログラムモードのテンプレートを GPM テンプレートに変換しやすくするために提供されています。たとえば、次のプログラムは上記のテンプレートと同じ出力を生成します。

program: finish_formatting(field("series_index"), "05.2f", " - ", " - ")

別の例:テンプレートの場合:

{series:re(([^\s])[^\s]+(\s|$),\1)}{series_index:0>2s| - | - }{title}

使用例:

program:
  strcat(
    re(field('series'), '([^\s])[^\s]+(\s|$)', '\1'),
    finish_formatting(field('series_index'), '0>2s', ' - ', ' - '),
    field('title')
  )

format_date

class calibre.utils.formatter_functions.BuiltinFormatDate[ソース]

format_date(value, format_string) -- format the value, which must be a date string, using the format_string, returning a string. It is best if the date is in ISO format as using other date formats often causes errors because the actual date value cannot be unambiguously determined. Note that the format_date_field() function is both faster and more reliable.

The formatting codes are:

  • d    : the day as number without a leading zero (1 to 31)

  • dd   : the day as number with a leading zero (01 to 31)

  • ddd  : the abbreviated localized day name (e.g. "Mon" to "Sun")

  • dddd : the long localized day name (e.g. "Monday" to "Sunday")

  • M    : the month as number without a leading zero (1 to 12)

  • MM   : the month as number with a leading zero (01 to 12)

  • MMM  : the abbreviated localized month name (e.g. "Jan" to "Dec")

  • MMMM : the long localized month name (e.g. "January" to "December")

  • yy   : the year as two digit number (00 to 99)

  • yyyy : the year as four digit number.

  • h    : the hours without a leading 0 (0 to 11 or 0 to 23, depending on am/pm)

  • hh   : the hours with a leading 0 (00 to 11 or 00 to 23, depending on am/pm)

  • m    : the minutes without a leading 0 (0 to 59)

  • mm   : the minutes with a leading 0 (00 to 59)

  • s    : the seconds without a leading 0 (0 to 59)

  • ss   : the seconds with a leading 0 (00 to 59)

  • ap   : use a 12-hour clock instead of a 24-hour clock, with 'ap' replaced by the lowercase localized string for am or pm

  • AP   : use a 12-hour clock instead of a 24-hour clock, with 'AP' replaced by the uppercase localized string for AM or PM

  • aP   : use a 12-hour clock instead of a 24-hour clock, with 'aP' replaced by the localized string for AM or PM

  • Ap   : use a 12-hour clock instead of a 24-hour clock, with 'Ap' replaced by the localized string for AM or PM

  • iso  : the date with time and timezone. Must be the only format present

  • to_number   : convert the date & time into a floating point number (a timestamp)

  • from_number : convert a floating point number (a timestamp) into an ISO-formatted date. If you want a different date format then add the desired formatting string after from_number and a colon (:). Example:

    format_date(val, 'from_number:MMM dd yyyy')
    

You might get unexpected results if the date you are formatting contains localized month names, which can happen if you changed the date format to contain MMMM. Using format_date_field() avoids this problem.

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "`" for italics on line 33 in "format_date"

format_date_field

class calibre.utils.formatter_functions.BuiltinFormatDateField[ソース]

format_date_field(field_name, format_string) -- フィールド field_name の値をフォーマットします。field_name は、標準またはカスタムの日付フィールドのルックアップ名である必要があります。 フォーマットコードについては、format_date() を参照してください。この関数は format_date() よりもはるかに高速で、フィールド (列) の値をフォーマットする場合に使用してください。また、基となる日付に直接作用するため、信頼性も高くなります。計算された日付や文字列変数内の日付には使用できません。例:

format_date_field('pubdate', 'yyyy.MM.dd')
format_date_field('#date_read', 'MMM dd, yyyy')

format_duration

class calibre.utils.formatter_functions.BuiltinFormatDuration[ソース]

format_duration(value, template, [largest_unit]) -- 秒数を表す数値valueを、週、日、時、分、秒を示す文字列にフォーマットします。valueが浮動小数点数の場合は、最も近い整数に丸められます。 値のフォーマット方法は、[``と]``で囲まれた値セレクターで構成されるテンプレートを使用して指定します。セレクターは次のとおりです。

  • [w]: 週

  • [d]: 日

  • [h]: 時

  • [m]: 分

  • [s]: 秒

セレクターの間には任意のテキストを入れることができます。

次の例では、2日(172,800秒)、1時間(3,600秒)、20秒の合計176,420秒の期間を使用しています。

  • format_duration(176420, '[d][h][m][s]')2d 1h 0m 20s を返します。

  • format_duration(176420, '[h][m][s]')49h 0m 20s を返します。

  • format_duration(176420, 'Your reading time is [d][h][m][s]')Your reading time is 49h 0m 20s を返します。

  • format_duration(176420, '[w][d][h][m][s]')2d 1h 0m 20s を返します。週の値がゼロの場合は表示されないことに注意してください。

上記の例のように、週などの項目でゼロ値を表示したい場合は、大文字のセレクターを使用します。たとえば、次の例では``'W'を使用してゼロ週を表示しています: ``format_duration(176420, '[W][d][h][m][s]')0w 2d 1h 0m 20s を返します。

デフォルトでは、値に続くテキストはセレクターとそれに続くスペースです。このテキストは好きなように変更できます。テキストを含むセレクターの形式は、セレクターの後にコロン、そして '|' 文字で区切られたテキストセグメントが続きます。出力に含めたいスペース文字はすべて含める必要があります。

テキストセグメントは1つから3つまで指定できます。

  • 1つのセグメントを指定した場合(例: [w: weeks ])、​​そのセグメントはすべての値に使用されます。

  • 2つのセグメントを指定した場合(例: [w: weeks | week ])、​​最初のセグメントは0と1より大きい値に使用され、2番目のセグメントは1に使用されます。

  • 3つのセグメントを指定した場合(例: [w: weeks | week | weeks ])、​​最初のセグメントは0、2番目のセグメントは1、3番目のセグメントは1より大きい値に使用されます。

多くの言語では、2番目の形式は3番目の形式と同等です。

例:

  • [w: weeks | week | weeks ]'0 weeks ''1 week '、または '2 weeks ' を生成します。

  • [w: weeks | week ]'0 weeks ''1 week '、または '2 weeks ' を生成します。

  • [w: weeks ]'0 weeks ''1 weeks '、または '2 weeks ' を生成します。

オプションの largest_unit パラメーターは、テンプレートによって生成される週、日、時間、分、秒のうち、最大の単位を指定します。これは値セレクターのいずれかである必要があります。これは値を切り捨てる場合に役立ちます。 format_duration(176420, '[h][m][s]', 'd') は、49h 0m 20s ではなく 1h 0m 20s を返します。

format_number

class calibre.utils.formatter_functions.BuiltinFormatNumber[ソース]

format_number(value, template) -- value を数値として解釈し、{0:5.2f}{0:,d}${0:5,.2f} などの Python フォーマットテンプレートを使用してその数値をフォーマットします。 フォーマットテンプレートは、上記の例のように {0: で始まり、} で終わる必要があります。例外: フォーマットテンプレートにフォーマットのみが含まれている場合は、先頭の "{0:" と末尾の "}" を省略できます。その他の例については、テンプレート言語Python のドキュメントを参照してください。フォーマットに失敗した場合は空の文字列を返します。

human_readable

class calibre.utils.formatter_functions.BuiltinHumanReadable[ソース]

human_readable(value) -- 引数 ``value``は数値を想定しており、その数値をKB、MB、GBなどの単位で表した文字列を返します。

rating_to_stars

class calibre.utils.formatter_functions.BuiltinRatingToStars[ソース]

rating_to_stars(value, use_half_stars) -- value を星印 () の文字列として返します。 value は 0 から 5 までの数値である必要があります。カスタム評価列で使用可能な小数値に半星印を使用する場合は、use_half_stars1 に設定してください。

値を反復処理

first_non_empty

class calibre.utils.formatter_functions.BuiltinFirstNonEmpty[ソース]

first_non_empty(value [, value]*) -- 空でない最初の value を返します。 すべての値が空の場合は、空の文字列が返されます。値はいくつでも指定できます。

lookup

class calibre.utils.formatter_functions.BuiltinLookup[ソース]

lookup(value, [ pattern, key, ]* else_key) -- パターンは、value に対して順番にチェックされます。 pattern が一致する場合は、key で指定されたフィールドの値が返されます。パターンが一致しない場合は、else_key で指定されたフィールドの値が返されます。switch() 関数も参照してください。

switch

class calibre.utils.formatter_functions.BuiltinSwitch[ソース]

switch(value, [patternN, valueN,]+ else_value) -- 各 patternN, valueN ペアについて、value が正規表現 patternN に一致するかどうかをチェックし、一致する場合は関連付けられた valueN を返します。一致する patternN がない場合は、else_value が返されます。patternN, valueN ペアはいくつでも指定できます。最初に一致したものが返されます。

switch_if

class calibre.utils.formatter_functions.BuiltinSwitchIf[ソース]

switch_if([test_expression, value_expression,]+ else_expression) -- 各 test_expression, value_expression ペアについて、test_expression が True (空でない) かどうかをチェックし、そうであれば value_expression の結果を返します。 test_expression が True でない場合は、else_expression の結果が返されます。test_expression, value_expression ペアはいくつでも指定できます。

再帰

eval

class calibre.utils.formatter_functions.BuiltinEval[ソース]

eval(string) -- 文字列をプログラムとして評価し、ローカル変数を渡します。 これにより、テンプレートプロセッサを使用してローカル変数から複雑な結果を構築できます。 テンプレート プログラム モード では、{} 文字はテンプレートが評価される前に解釈されるため、{ 文字には [[ を、} 文字には ]] を使用する必要があります。これらは自動的に変換されます。また、テンプレート プログラム モードを使用する場合、この関数の引数にプレフィックスとサフィックス (|prefix|suffix 構文) を使用することはできません。

template

class calibre.utils.formatter_functions.BuiltinTemplate[ソース]

template(x) -- evaluates x as a template. The evaluation is done in its own context, meaning that variables are not shared between the caller and the template evaluation. If not using General Program Mode, because the { and } characters are special, you must use [[ for the { character and ]] for the } character; they are converted automatically. For example, template(\'[[title_sort]]\') will evaluate the template {title_sort} and return its value. Note also that prefixes and suffixes (the |prefix|suffix syntax) cannot be used in the argument to this function when using template program mode.

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "``" for CODE_TEXT on line 1 in "template"

文字列操作

character

class calibre.utils.formatter_functions.BuiltinCharacter[ソース]

character(character_name) -- returns the character named by character_name. For example, character('newline') returns a newline character ('\n'). The supported character names are newline, return, tab, and backslash. This function is used to put these characters into the output of templates.

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "`" for italics on line 2 in "character"

check_yes_no

class calibre.utils.formatter_functions.BuiltinCheckYesNo[ソース]

check_yes_no(field_name, is_undefined, is_false, is_true) -- 検索名 field_name で指定されたYes/Noフィールドの値が、パラメータで指定されたいずれかの値と一致するかどうかをチェックします。 一致する場合は 'Yes' を返し、一致しない場合は空の文字列を返します。パラメータ is_undefinedis_false、または is_true を 1 (数値) に設定すると、それぞれの条件をチェックします。それ以外の場合は 0 を設定します。 例: check_yes_no("#bool", 1, 0, 1) は、Yes/Noフィールド #bool が True または未定義 (True でも False でもない) の場合、'Yes' を返します。 is_undefinedis_false、または is_true のうち複数個に 1 を設定することも可能です。

contains

class calibre.utils.formatter_functions.BuiltinContains[ソース]

contains(value, pattern, text_if_match, text_if_not_match) -- 値が正規表現 pattern に一致するかどうかをチェックします。 パターンが値に一致する場合は text_if_match を返し、一致しない場合は text_if_not_match を返します。

field_exists

class calibre.utils.formatter_functions.BuiltinFieldExists[ソース]

`field_exists(lookup_name) -- 指定されたルックアップ名 lookup_name を持つフィールド(列)が存在するかどうかを確認し、存在する場合は '1' を、存在しない場合は空の文字列を返します。

ifempty

class calibre.utils.formatter_functions.BuiltinIfempty[ソース]

ifempty(value, text_if_empty) -- value が空でない場合はその value を返し、そうでない場合は text_if_empty を返します。

re

class calibre.utils.formatter_functions.BuiltinRe[ソース]

re(value, pattern, replacement) -- 正規表現を適用した後の value を返します。 value 内の pattern のすべてのインスタンスは replacement に置き換えられます。テンプレート言語は、大文字小文字を区別しない Python 正規表現 を使用します。

re_group

class calibre.utils.formatter_functions.BuiltinReGroup[ソース]

re_group(value, pattern [, template_for_group]*) -- value に正規表現 pattern を適用し、一致した各インスタンスを対応するテンプレートから返された値に置き換えた文字列を返します。テンプレートプログラムモード <https://manual.calibre-ebook.com/template_lang.html#more-complex-programs-in-template-expressions-template-program-mode>`_では、``template` 関数や eval 関数と同様に、{ の代わりに [[ を、} の代わりに ]] を使用します。

次の例では、複数の単語を含むシリーズを検索し、最初の単語を大文字に変換します。

program: re_group(field('series'), "(\S* )(.*)", "{$:uppercase()}", "{$}")'}

shorten

class calibre.utils.formatter_functions.BuiltinShorten[ソース]

shorten(value, left_chars, middle_text, right_chars) -- value を短縮したバージョンを返します。短縮されたバージョンは、value の先頭から left_chars 文字、middle_textvalue の末尾から right_chars 文字で構成されます。left_charsright_chars は負でない整数である必要があります。

例:タイトルを最大 15 文字の長さで表示したいとします。これを実現するテンプレートの 1 つは、{title:shorten(9,-,5)} です。タイトルが Ancient English Laws in the Times of Ivanhoe の場合、結果は Ancient E-anhoe となります。これは、タイトルの最初の 9 文字、-、そして最後の 5 文字で構成されています。値の長さが "左文字" + "右文字" +"中央テキスト" の長さよりも短い場合、値は変更されずに返されます。例えば、タイトル 'The Dome' は変更されません。

strcat

class calibre.utils.formatter_functions.BuiltinStrcat[ソース]

strcat(a [, b]*) -- すべての引数を連結して作成された文字列を返します。 引数の数は任意です。ほとんどの場合、この関数の代わりに & 演算子を使用できます。

strcat_max

class calibre.utils.formatter_functions.BuiltinStrcatMax[ソース]

strcat_max(max, string1 [, prefix2, string2]*) -- 引数を連結して文字列を生成します。 返される値は string1 で初期化されます。 prefix, string のペアから生成された文字列は、結果として得られる文字列の長さが max より短い限り、値の末尾に追加されます。prefix は空でも構いません。 string1max より長い場合でも string1 を返します。 prefix, string のペアはいくつでも渡すことができます。

strlen

class calibre.utils.formatter_functions.BuiltinStrlen[ソース]

strlen(value) -- 文字列 value の長さを返します。

substr

class calibre.utils.formatter_functions.BuiltinSubstr[ソース]

substr(value, start, end) -- valuestart 番目から end 番目までの文字を返します。 value の最初の文字は、0 番目の文字です。 end が負の値の場合は、右から数えてその文字数だけであることを示します。 end がゼロの場合は、最後の文字を示します。たとえば、substr('12345', 1, 0)'2345' を返し、substr('12345', 1, -1)'234' を返します。

swap_around_articles

class calibre.utils.formatter_functions.BuiltinSwapAroundArticles[ソース]

swap_around_articles(value, separator) -- セミコロンで区切られた記事が末尾に移動された value を返します。 value はリストにすることができます。その場合、リスト内の各項目が処理されます。value がリストの場合は、separator を指定する必要があります。separator が指定されていない場合、または区切り文字が空文字列の場合は、value はリストではなく単一の値として扱われます。articles は、calibre が title_sort を生成するために使用するものです。

swap_around_comma

class calibre.utils.formatter_functions.BuiltinSwapAroundComma[ソース]

swap_around_comma(value) -- B, A の形式の value が与えられた場合、A B を返します。 これは、LN、FN 形式の名前を FN LN に変換する場合に最も便利です。value にカンマがない場合、この関数は値を変更せずに返します。

test

class calibre.utils.formatter_functions.BuiltinTest[ソース]

test(value, text_if_not_empty, text_if_empty) -- 値が空でない場合は text_if_not_empty を返し、そうでない場合は text_if_empty を返します。

transliterate

class calibre.utils.formatter_functions.BuiltinTransliterate[ソース]

transliterate(value) -- value に含まれる単語の音を近似してラテン文字で文字列を生成します。 例えば、valueФёдор Миха́йлович Достоевский の場合、この関数は Fiodor Mikhailovich Dostoievskii を返します。

日付関数

date_arithmetic

class calibre.utils.formatter_functions.BuiltinDateArithmetic[ソース]

date_arithmetic(value, calc_spec, fmt) -- value を基に calc_spec を使用して新しい日付を計算します。 オプションの fmt に従ってフォーマットされた新しい日付を返します。fmt が指定されていない場合は、結果はISO形式になります。calc_spec は、vW (valueWhat) のペアを連結した文字列です。ここで、v は負の数を含む可能性のある数値、W は次のいずれかの文字です。

  • s: datev 秒を加算します。

  • m: datev 分を加算します。

  • h: datev 時間を加算します。

  • d: datev 日を加算します。

  • w: datev 週を加算します。

  • y: datev 年を加算します(1年は365日とします)。

例: '1s3d-1m' は、date に1秒、3日を加算し、1分を減算します。

days_between

class calibre.utils.formatter_functions.BuiltinDaysBetween[ソース]

days_between(date1, date2) -- return the number of days between date1 and date2. The number is positive if date1 is greater than date2, otherwise negative. If either date1 or date2 are not dates, the function returns the empty string.

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "``" for CODE_TEXT on line 2 in "days_between"

today

class calibre.utils.formatter_functions.BuiltinToday[ソース]

today() -- 今日 (現在) の日時文字列を返します。 この値は format_date または days_between で使用するために設計されていますが、他の文字列と同様に操作できます。日付は ISO 日時形式です。

書誌データから値を取得する

author_sorts

class calibre.utils.formatter_functions.BuiltinAuthorSorts[ソース]

author_sorts(val_separator) -- 著者のソート値をリストにした文字列を返します。ソート値は著者メタデータ情報に記載されているもので、本の著者ソート値とは異なる場合があります。返されるリストは author sort 1 val_separator author sort 2 などという形式で、余分なスペースは含まれません。このリスト内の著者ソート値は、本の著者と同じ順序になっています。 val_separator の前後にスペースが必要な場合は、 val_separator 文字列にスペースを含めてください。

booksize

class calibre.utils.formatter_functions.BuiltinBooksize[ソース]

booksize() -- calibreの size フィールドの値を返します。本にフォーマットがない場合は空の文字列を返します。 この関数はGUIでのみ動作します。この値をディスクへの保存テンプレートまたはデバイスへの送信テンプレートで使用したい場合は、カスタムの 他の列から作成された列 を作成し、その列のテンプレート内でこの関数を使用し、保存/送信テンプレートではその列の値を使用する必要があります。

connected_device_name

class calibre.utils.formatter_functions.BuiltinConnectedDeviceName[ソース]

connected_device_name(storage_location_key) -- デバイスが接続されている場合はデバイス名を返し、そうでない場合は空の文字列を返します。 デバイス上の各格納場所には、それぞれ独自のデバイス名があります。storage_location_key の名前は 'main''carda''cardb' です。この関数はGUIでのみ動作します。

connected_device_uuid

class calibre.utils.formatter_functions.BuiltinConnectedDeviceUUID[ソース]

connected_device_uuid(storage_location_key) -- if a device is connected then return the device uuid (unique id), otherwise return the empty string. Each storage location on a device has a different uuid. The storage_location_key location names are 'main', 'carda' and 'cardb'. This function works only in the GUI.

FFML エラーのため、ドキュメントを英語で表示します。 Missing closing "``" for CODE_TEXT on line 1 in "connected_device_uuid"

current_library_name

class calibre.utils.formatter_functions.BuiltinCurrentLibraryName[ソース]

current_library_name() -- 現在の calibre ライブラリへのパスの最後の名前を返します。

current_library_path

class calibre.utils.formatter_functions.BuiltinCurrentLibraryPath[ソース]

current_library_path() -- 現在の calibre ライブラリへのフルパスを返します。

current_virtual_library_name

class calibre.utils.formatter_functions.BuiltinCurrentVirtualLibraryName[ソース]

current_virtual_library_name() -- 現在の仮想ライブラリが存在する場合はその名前を返し、存在しない場合は空の文字列を返します。 ライブラリ名の大文字・小文字は保持されます。例:

program: current_virtual_library_name()

この関数はGUI環境でのみ動作します。

field

class calibre.utils.formatter_functions.BuiltinField[ソース]

field(lookup_name) -- ルックアップ名 lookup_name を持つ書誌データフィールドの値を返します。 関数名の代わりに $ プレフィックスを使用することもできます。例: $tags

has_cover

class calibre.utils.formatter_functions.BuiltinHasCover[ソース]

has_cover() -- 本に表紙があれば 'Yes' を返し、そうでなければ空の文字列を返します。

is_marked

class calibre.utils.formatter_functions.BuiltinIsMarked[ソース]

is_marked() -- calibreで本が マーク済み かどうかを確認します。 マークされている場合は、マークの値(小文字の 'true' または名前付きマークのカンマ区切りリスト)を返します。マークされていない場合は、'' 空文字列)を返します。この関数はGUIでのみ動作します。

language_codes

class calibre.utils.formatter_functions.BuiltinLanguageCodes[ソース]

language_codes(lang_strings) -- lang_strings で渡された言語名に対応する 言語コード を返します。 文字列は現在のロケールの言語で記述されている必要があります。 lang_strings はカンマ区切りのリストです。

language_strings

class calibre.utils.formatter_functions.BuiltinLanguageStrings[ソース]

language_strings(value, localize) -- value``で渡された言語コード(`言語名とコードはこちらを参照 <https://www.loc.gov/standards/iso639-2/php/code_list.php>`_ )に対応する言語名を返します。 例: ``{languages:language_strings()}localize がゼロの場合は、文字列を英語で返します。 localize がゼロ以外の場合は、現在のロケールの言語で文字列を返します。 lang_codes はカンマ区切りのリストです。

ondevice

class calibre.utils.formatter_functions.BuiltinOndevice[ソース]

ondevice() -- ondevice が設定されている場合は文字列 'Yes' を返し、そうでない場合は空の文字列を返します。 この関数は GUI でのみ機能します。この値をディスクへの保存またはデバイスへの送信テンプレートで使用する場合は、カスタムの「他の列から構築された列」を作成し、その列のテンプレートで関数を使用し、その列の値を保存/送信テンプレートで使用する必要があります。

raw_field

class calibre.utils.formatter_functions.BuiltinRawField[ソース]

raw_field(lookup_name [, optional_default]) -- lookup_name で指定された書誌データ フィールドを、書式設定を適用せずに返します。 フィールドの値が未定義 ( None ) の場合は、オプションの 2 番目の引数 optional_default を評価して返します。$$ プレフィックスは、$$pubdate のように、関数の代わりに使用できます。

raw_list

class calibre.utils.formatter_functions.BuiltinRawList[ソース]

raw_list(lookup_name, separator) -- 指定された名前 lookup_name の書誌データリストを、フォーマットやソートを一切適用せずに返します。 リストの各項目は separator で区切られます。

series_sort

class calibre.utils.formatter_functions.BuiltinSeriesSort[ソース]

series_sort() -- シリーズ読みの値を返します。

user_categories

class calibre.utils.formatter_functions.BuiltinUserCategories[ソース]

user_categories() -- この書籍を含むユーザーカテゴリをカンマ区切りのリストで返します。 この関数は GUI でのみ機能します。これらの値をディスクへの保存またはデバイスへの送信テンプレートで使用する場合は、カスタムの 他の列から構築された列 を作成し、その列のテンプレートで関数を使用し、その列の値を保存/送信テンプレートで使用する必要があります。

virtual_libraries

class calibre.utils.formatter_functions.BuiltinVirtualLibraries[ソース]

virtual_libraries() -- この書籍を含む仮想ライブラリをカンマ区切りのリストで返します。 この関数は GUI でのみ機能します。これらの値をディスクへの保存またはデバイスへの送信テンプレートで使用する場合は、カスタムの 他の列から構築された列 を作成し、その列のテンプレートで関数を使用し、その列の値を保存/送信テンプレートで使用する必要があります。

算術

add

class calibre.utils.formatter_functions.BuiltinAdd[ソース]

add(x [, y]*) -- 引数の合計を返します。 引数のいずれかが数値でない場合は例外が発生します。ほとんどの場合、この関数の代わりに + 演算子を使用できます。

ceiling

class calibre.utils.formatter_functions.BuiltinCeiling[ソース]

ceiling(value) -- value 以上の最小の整数を返します。 ``value``が数値でない場合は例外が発生します。

divide

class calibre.utils.formatter_functions.BuiltinDivide[ソース]

divide(x, y) ―― x / y の結果を返します。x または y``のいずれかが数値でない場合は例外を発生します。この関数は通常、 ``/ 演算子で置き換えることができます。

floor

class calibre.utils.formatter_functions.BuiltinFloor[ソース]

floor(value) -- value 以下の最大の整数を返します。value が数値でない場合は例外が発生します。

fractional_part

class calibre.utils.formatter_functions.BuiltinFractionalPart[ソース]

fractional_part(value) -- 値の小数点以下の部分を返します。 例えば、fractional_part(3.14)0.14 を返します。 value が数値でない場合は例外を発生します。

mod

class calibre.utils.formatter_functions.BuiltinMod[ソース]

mod(value, y) -- value / y``の剰余の小数点以下を切り捨てた値を返します。``value または y のいずれかが数値でない場合は例外を発生します。

multiply

class calibre.utils.formatter_functions.BuiltinMultiply[ソース]

multiply(x [, y]*) -- 引数の積を返します。 いずれかの引数が数値でない場合は例外を発生します。この関数は通常、 * 演算子で置き換えることができます。

round

class calibre.utils.formatter_functions.BuiltinRound[ソース]

round(value) -- value``に最も近い整数を返します。``value が数値でない場合は例外が発生します。

subtract

class calibre.utils.formatter_functions.BuiltinSubtract[ソース]

subtract(x, y) -- x - y を返します。 x または y のいずれかが数値でない場合は例外をスローします。この関数は通常、- 演算子で置き換えることができます。

API of the Metadata objects

The python implementation of the template functions is passed in a Metadata object. Knowing it's API is useful if you want to define your own template functions.

class calibre.ebooks.metadata.book.base.Metadata(title, authors=('不明',), other=None, template_cache=None, formatter=None)[ソース]

A class representing all the metadata for a book. The various standard metadata fields are available as attributes of this object. You can also stick arbitrary attributes onto this object.

Metadata from custom columns should be accessed via the get() method, passing in the lookup name for the column, for example: "#mytags".

Use the is_null() method to test if a field is null.

This object also has functions to format fields into strings.

The list of standard metadata fields grows with time is in STANDARD_METADATA_FIELDS.

Please keep the method based API of this class to a minimum. Every method becomes a reserved field name.

is_null(field)[ソース]

Return True if the value of field is null in this object. 'null' means it is unknown or evaluates to False. So a title of _('Unknown') is null or a language of 'und' is null.

Be careful with numeric fields since this will return True for zero as well as None.

Also returns True if the field does not exist.

deepcopy(class_generator=<function Metadata.<lambda>>)[ソース]

Do not use this method unless you know what you are doing, if you want to create a simple clone of this object, use deepcopy_metadata() instead. Class_generator must be a function that returns an instance of Metadata or a subclass of it.

get_identifiers()[ソース]

Return a copy of the identifiers dictionary. The dict is small, and the penalty for using a reference where a copy is needed is large. Also, we don't want any manipulations of the returned dict to show up in the book.

set_identifiers(identifiers)[ソース]

Set all identifiers. Note that if you previously set ISBN, calling this method will delete it.

set_identifier(typ, val)[ソース]

If val is empty, deletes identifier of type typ

standard_field_keys()[ソース]

return a list of all possible keys, even if this book doesn't have them

custom_field_keys()[ソース]

return a list of the custom fields in this book

all_field_keys()[ソース]

All field keys known by this instance, even if their value is None

metadata_for_field(key)[ソース]

return metadata describing a standard or custom field.

all_non_none_fields()[ソース]

Return a dictionary containing all non-None metadata fields, including the custom ones.

get_standard_metadata(field, make_copy)[ソース]

return field metadata from the field if it is there. Otherwise return None. field is the key name, not the label. Return a copy if requested, just in case the user wants to change values in the dict.

get_all_standard_metadata(make_copy)[ソース]

return a dict containing all the standard field metadata associated with the book.

get_all_user_metadata(make_copy)[ソース]

return a dict containing all the custom field metadata associated with the book.

get_user_metadata(field, make_copy)[ソース]

return field metadata from the object if it is there. Otherwise return None. field is the key name, not the label. Return a copy if requested, just in case the user wants to change values in the dict.

set_all_user_metadata(metadata)[ソース]

store custom field metadata into the object. Field is the key name not the label

set_user_metadata(field, metadata)[ソース]

store custom field metadata for one column into the object. Field is the key name not the label

remove_stale_user_metadata(other_mi)[ソース]

Remove user metadata keys (custom column keys) if they don't exist in 'other_mi', which must be a metadata object

template_to_attribute(other, ops)[ソース]

Takes a list [(src,dest), (src,dest)], evaluates the template in the context of other, then copies the result to self[dest]. This is on a best-efforts basis. Some assignments can make no sense.

smart_update(other, replace_metadata=False)[ソース]

Merge the information in other into self. In case of conflicts, the information in other takes precedence, unless the information in other is NULL.

format_field(key, series_with_index=True)[ソース]

Returns the tuple (display_name, formatted_value)

to_html()[ソース]

A HTML representation of this object.

calibre.ebooks.metadata.book.base.STANDARD_METADATA_FIELDS

The set of standard metadata fields.


'''
All fields must have a NULL value represented as None for simple types,
an empty list/dictionary for complex types and (None, None) for cover_data
'''

SOCIAL_METADATA_FIELDS = frozenset((
    'tags',             # Ordered list
    'rating',           # A floating point number between 0 and 10
    'comments',         # A simple HTML enabled string
    'series',           # A simple string
    'series_index',     # A floating point number
    # Of the form { scheme1:value1, scheme2:value2}
    # For example: {'isbn':'123456789', 'doi':'xxxx', ... }
    'identifiers',
))

'''
The list of names that convert to identifiers when in get and set.
'''

TOP_LEVEL_IDENTIFIERS = frozenset((
    'isbn',
))

PUBLICATION_METADATA_FIELDS = frozenset((
    'title',            # title must never be None. Should be _('Unknown')
    # Pseudo field that can be set, but if not set is auto generated
    # from title and languages
    'title_sort',
    'authors',          # Ordered list. Must never be None, can be [_('Unknown')]
    'author_sort_map',  # Map of sort strings for each author
    # Pseudo field that can be set, but if not set is auto generated
    # from authors and languages
    'author_sort',
    'book_producer',
    'timestamp',        # Dates and times must be timezone aware
    'pubdate',
    'last_modified',
    'rights',
    # So far only known publication type is periodical:calibre
    # If None, means book
    'publication_type',
    'uuid',             # A UUID usually of type 4
    'languages',        # ordered list of languages in this publication
    'publisher',        # Simple string, no special semantics
    # Absolute path to image file encoded in filesystem_encoding
    'cover',
    # Of the form (format, data) where format is, e.g. 'jpeg', 'png', 'gif'...
    'cover_data',
    # Either thumbnail data, or an object with the attribute
    # image_path which is the path to an image file, encoded
    # in filesystem_encoding
    'thumbnail',
))

BOOK_STRUCTURE_FIELDS = frozenset((
    # These are used by code, Null values are None.
    'toc', 'spine', 'guide', 'manifest',
))

USER_METADATA_FIELDS = frozenset((
    # A dict of dicts similar to field_metadata. Each field description dict
    # also contains a value field with the key #value#.
    'user_metadata',
))

DEVICE_METADATA_FIELDS = frozenset((
    'device_collections',   # Ordered list of strings
    'lpath',                # Unicode, / separated
    'size',                 # In bytes
    'mime',                 # Mimetype of the book file being represented
))

CALIBRE_METADATA_FIELDS = frozenset((
    'application_id',   # An application id, currently set to the db_id.
    'db_id',            # the calibre primary key of the item.
    'formats',          # list of formats (extensions) for this book
    # a dict of user category names, where the value is a list of item names
    # from the book that are in that category
    'user_categories',
    # a dict of items to associated hyperlink
    'link_maps',
    # Calculated page count, null values are None or 0. -1 is no countable
    # formats. -2 is error processing formats, -3 is DRMed.
    'pages',
))

ALL_METADATA_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           USER_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# All fields except custom fields
STANDARD_METADATA_FIELDS = SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# Metadata fields that smart update must do special processing to copy.
SC_FIELDS_NOT_COPIED =     frozenset(('title', 'title_sort', 'authors',
                                      'author_sort', 'author_sort_map',
                                      'cover_data', 'tags', 'languages',
                                      'identifiers'))

# Metadata fields that smart update should copy only if the source is not None
SC_FIELDS_COPY_NOT_NULL =  frozenset(('device_collections', 'lpath', 'size', 'comments', 'thumbnail'))

# Metadata fields that smart update should copy without special handling
SC_COPYABLE_FIELDS =       SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS) - \
                           SC_FIELDS_NOT_COPIED.union(
                           SC_FIELDS_COPY_NOT_NULL)

SERIALIZABLE_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           USER_METADATA_FIELDS).union(
                           PUBLICATION_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS) - \
                           frozenset(('device_collections', 'formats',
                               'cover_data'))
# these are rebuilt when needed