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.

Boolean

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]*) -- returns the string '1' if any value is not empty, otherwise returns the empty string. You can have as many values as you want. This function can usually be replaced by the || operator. A reason it cannot be replaced is if short-circuiting will change the results because of side effects.

Case changes

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) -- returns the value in title case.

uppercase

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

uppercase(value) -- returns the value in upper case.

Database functions

annotation_count

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

annotation_count() -- return the total number of annotations of all types attached to the current book. This function works only in the GUI and the content server.

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.

Showing the documentation in English because of the FFML error: 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.

Showing the documentation in English because of the FFML error: 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およびコンテンツサーバーでのみ動作します。

Date functions

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.

Showing the documentation in English because of the FFML error: Missing closing "``" for CODE_TEXT on line 2 in "days_between"

today

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

today() -- return a date+time string for today (now). This value is designed for use in format_date or days_between, but can be manipulated like any other string. The date is in ISO date/time format.

Formatting values

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

Showing the documentation in English because of the FFML error: Missing closing "`" for italics on line 22 in "f_string"

finish_formatting

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

finish_formatting(value, format, prefix, suffix) -- apply the format, prefix, and suffix to the value in the same way as done in a template like {series_index:05.2f| - |- }. This function is provided to ease conversion of complex single-function- or template-program-mode templates to GPM Templates. For example, the following program produces the same output as the above template:

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

Another example: for the template:

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

use:

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.

Showing the documentation in English because of the FFML error: 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) -- format the value in the field field_name, which must be the lookup name of a date field, either standard or custom. See format_date() for the formatting codes. This function is much faster than format_date() and should be used when you are formatting the value in a field (column). It is also more reliable because it works directly on the underlying date. It can't be used for computed dates or dates in string variables. Examples:

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) -- Returns the value as string of star () characters. The value must be a number between 0 and 5. Set use_half_stars to 1 if you want half star characters for fractional numbers available with custom ratings columns.

GUI functions

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]*) -- returns the list of book ids sorted by the column specified by the lookup name in sorted_by in the order specified by ascending. If ascending is '1' then the books are sorted by the value in the 'sorted_by' column in ascending order, otherwise in descending order. You can have multiple pairs of sorted_by, ascending. The first pair specifies the major order.

This function can be used only in the GUI.

Get values from metadata

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.

Showing the documentation in English because of the FFML error: 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() -- return the string 'Yes' if ondevice is set, otherwise return the empty string. This function works only in the GUI. If you want to use this value in save-to-disk or send-to-device templates then you must make a custom "Column built from other columns", use the function in that column's template, and use that column's value in your save/send templates.

raw_field

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

raw_field(lookup_name [, optional_default]) -- returns the metadata field named by lookup_name without applying any formatting. It evaluates and returns the optional second argument optional_default if the field's value is undefined (None). The $$ prefix can be used instead of the function, as in $$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() -- return a comma-separated list of the user categories that contain this book. This function works only in the GUI. If you want to use these values in save-to-disk or send-to-device templates then you must make a custom Column built from other columns, use the function in that column's template, and use that column's value in your save/send templates

virtual_libraries

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

virtual_libraries() -- return a comma-separated list of Virtual libraries that contain this book. This function works only in the GUI. If you want to use these values in save-to-disk or send-to-device templates then you must make a custom Column built from other columns, use the function in that column's template, and use that column's value in your save/send templates.

Iterate over values

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) -- The patterns will be checked against the value in order. If a pattern matches then the value of the field named by key is returned. If no pattern matches then the value of the field named by else_key is returned. See also the switch() function.

switch

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

switch(value, [patternN, valueN,]+ else_value) -- for each patternN, valueN pair, checks if the value matches the regular expression patternN and if so returns the associated valueN. If no patternN matches, then else_value is returned. You can have as many patternN, valueN pairs as you wish. The first match is returned.

switch_if

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

switch_if([test_expression, value_expression,]+ else_expression) -- for each test_expression, value_expression pair, checks if test_expression is True (non-empty) and if so returns the result of value_expression. If no test_expression is True then the result of else_expression is returned. You can have as many test_expression, value_expression pairs as you want.

List lookup

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) -- interpret the value as a list of items separated by separator, checking the pattern against each item in the list. If the pattern matches an item then return found_val, otherwise return not_found_val. The pair pattern and found_value can be repeated as many times as desired, permitting returning different values depending on the item's value. The patterns are checked in order, and the first match is returned.

Aliases: in_list(), list_contains()

list_item

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

list_item(value, index, separator) -- interpret the value as a list of items separated by separator, returning the 'index'th item. The first item is number zero. The last item has the index -1 as in list_item(-1,separator). If the item is not in the list, then the empty string is returned. The separator has the same meaning as in the count function, usually comma but is ampersand for author-like lists.

select

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

select(value, key) -- interpret the value as a comma-separated list of items with each item having the form id:id_value (the calibre identifier format). The function finds the first pair with the id equal to key and returns the corresponding id_value. If no id matches then the function returns the empty string.

str_in_list

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

str_in_list(value, separator, [ string, found_val, ]+ not_found_val) -- interpret the value as a list of items separated by separator then compare string against each value in the list. The string is not a regular expression. If string is equal to any item (ignoring case) then return the corresponding found_val. If string contains separators then it is also treated as a list and each subvalue is checked. The string and found_value pairs can be repeated as many times as desired, permitting returning different values depending on string's value. If none of the strings match then not_found_value is returned. The strings are checked in order. The first match is returned.

List manipulation

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()

Showing the documentation in English because of the FFML error: 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) -- return yes_val if list1 and list2 contain the same items, otherwise return no_val. The items are determined by splitting each list using the appropriate separator character (sep1 or sep2). The order of items in the lists is not relevant. The comparison is case-insensitive.

list_intersection

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

list_intersection(list1, list2, separator) -- return a list made by removing from list1 any item not found in list2 using a case-insensitive comparison. The items in list1 and list2 are separated by separator, as are the items in the returned list.

list_join

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

list_join(with_separator, list1, separator1 [, list2, separator2]*) -- return a list made by joining the items in the source lists (list1 etc) using with_separator between the items in the result list. Items in each source list[123...] are separated by the associated separator[123...]. A list can contain zero values. It can be a field like publisher that is single-valued, effectively a one-item list. Duplicates are removed using a case-insensitive comparison. Items are returned in the order they appear in the source lists. If items on lists differ only in letter case then the last is used. All separators can be more than one character.

Example:

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

You can use list_join on the results of previous calls to list_join as follows:

program:
    a = list_join('#@#', $authors, '&', $tags, ',');
    b = list_join('#@#', a, '#@#', $#genre, ',', $#people, '&', 'some value', ',')

You can use expressions to generate a list. For example, assume you want items for authors and #genre, but with the genre changed to the word "Genre: " followed by the first letter of the genre, i.e. the genre "Fiction" becomes "Genre: F". The following will do that:

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) -- Construct a list by first separating src_list into items using the separator character. For each item in the list, check if it matches include_re. If it does then add it to the list to be returned. If opt_replace is not the empty string then apply the replacement before adding the item to the returned list.

list_re_group

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

list_re_group(src_list, separator, include_re, search_re [,template_for_group]*) -- Like list_re() except replacements are not optional. It uses re_group(item, search_re, template ...) when doing the replacements.

list_remove_duplicates

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

list_remove_duplicates(list, separator) -- return a list made by removing duplicate items in list. If items differ only in case then the last is returned. The items in list are separated by separator, as are the items in the returned list.

list_sort

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

list_sort(value, direction, separator) -- return value sorted using a case-insensitive lexical sort. If direction is zero (number or character), value is sorted ascending, otherwise descending. The list items are separated by separator, as are the items in the returned list.

list_split

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

list_split(list_val, sep, id_prefix) -- splits list_val into separate values using sep, then assigns the values to local variables named id_prefix_N where N is the position of the value in the list. The first item has position 0 (zero). The function returns the last element in the list.

Example:

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

is equivalent to:

var_0 = 'one'
    var_1 = 'two'
    var_2 = 'foo'

list_union

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

list_union(list1, list2, separator) -- return a list made by merging the items in list1 and list2, removing duplicate items using a case-insensitive comparison. If items differ in case, the one in list1 is used. The items in list1 and list2 are separated by separator, as are the items in the returned list.

Aliases: merge_lists(), list_union()

range

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

range(start, stop, step, limit) -- returns a list of numbers generated by looping over the range specified by the parameters start, stop, and step, with a maximum length of limit. The first value produced is 'start'. Subsequent values next_v = current_v + step. The loop continues while next_v < stop assuming step is positive, otherwise while next_v > stop. An empty list is produced if start fails the test: start >= stop if step is positive. The limit sets the maximum length of the list and has a default of 1000. The parameters start, step, and limit are optional. Calling range() with one argument specifies stop. Two arguments specify start and stop. Three arguments specify start, stop, and step. Four arguments specify start, stop, step and limit.

Examples:

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) -- This function breaks apart lists of tag-like hierarchical items such as genres. It interprets the value as a comma- separated list of tag-like items, where each item is a period-separated list. It returns a new list made by extracting from each item the components from start_index to end_index, then merging the results back together. Duplicates are removed. The first subitem in a period-separated list has an index of zero. If an index is negative then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list.

Examples:

  • Assuming a #genre column containing "A.B.C":

    • {#genre:subitems(0,1)} returns "A"

    • {#genre:subitems(0,2)} returns "A.B"

    • {#genre:subitems(1,0)} returns "B.C"

  • Assuming a #genre column containing "A.B.C, D.E":

    • {#genre:subitems(0,1)} returns "A, D"

    • {#genre:subitems(0,2)} returns "A.B, D.E"

sublist

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

sublist(value, start_index, end_index, separator) -- interpret the value as a list of items separated by separator, returning a new list made from the items from start_index to end_index. The first item is number zero. If an index is negative, then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list.

Examples assuming that the tags column (which is comma-separated) contains "A, B, C":

  • {tags:sublist(0,1,\,)} returns "A"

  • {tags:sublist(-1,0,\,)} returns "C"

  • {tags:sublist(0,-1,\,)} returns "A, B"

Recursion

eval

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

eval(string) -- evaluates the string as a program, passing the local variables. This permits using the template processor to construct complex results from local variables. In Template Program Mode, because the { and } characters are interpreted before the template is evaluated you must use [[ for the { character and ]] for the } character. They are converted automatically. Note also that prefixes and suffixes (the |prefix|suffix syntax) cannot be used in the argument to this function when using Template Program Mode.

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.

Relational

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) -- does a case-insensitive lexical comparison of x and y. Returns lt if x < y, eq if x == y, otherwise gt. This function can often be replaced by one of the lexical comparison operators (==, >, <, etc.)

strcmpcase

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

strcmpcase(x, y, lt, eq, gt) -- does a case-sensitive lexical comparison of x and y. Returns lt if x < y, eq if x == y, otherwise gt.

Note: This is NOT the default behavior used by calibre, for example, in the lexical comparison operators (==, >, <, etc.). This function could cause unexpected results, preferably use strcmp() whenever possible.

String manipulation

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.

Showing the documentation in English because of the FFML error: 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) -- return the value after applying the regular expression. All instances of pattern in the value are replaced with replacement. The template language uses case insensitive Python regular expressions.

re_group

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

re_group(value, pattern [, template_for_group]*) -- return a string made by applying the regular expression pattern to value and replacing each matched instance with the value returned by the corresponding template. In Template Program Mode, like for the template and the eval functions, you use [[ for { and ]] for }.

The following example looks for a series with more than one word and uppercases the first word:

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

shorten

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

shorten(value, left_chars, middle_text, right_chars) -- Return a shortened version of the value, consisting of left_chars characters from the beginning of the value, followed by middle_text, followed by right_chars characters from the end of the value. left_chars and right_chars must be non-negative integers.

Example: assume you want to display the title with a length of at most 15 characters in length. One template that does this is {title:shorten(9,-,5)}. For a book with the title Ancient English Laws inthe Times of Ivanhoe the result will be Ancient E-anhoe: the first 9 characters of the title, a -, then the last 5 characters. If the value's length is less than left chars + right chars + the length of middle text then the value will be returned unchanged. For example, the title TheDome would not be changed.

strcat

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

strcat(a [, b]*) -- returns a string formed by concatenating all the arguments. Can take any number of arguments. In most cases you can use the & operator instead of this function.

strcat_max

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

strcat_max(max, string1 [, prefix2, string2]*) -- Returns a string formed by concatenating the arguments. The returned value is initialized to string1. Strings made from prefix, string pairs are added to the end of the value as long as the resulting string length is less than max. Prefixes can be empty. Returns string1 even if string1 is longer than max. You can pass as many prefix, string pairs as you wish.

strlen

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

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

substr

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

substr(value, start, end) -- returns the start'th through the end'th characters of value. The first character in value is the zero'th character. If end is negative then it indicates that many characters counting from the right. If end is zero, then it indicates the last character. For example, substr('12345', 1, 0) returns '2345', and substr('12345', 1, -1) returns '234'.

swap_around_articles

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

swap_around_articles(value, separator) -- returns the value with articles moved to the end, separated by a semicolon. The value can be a list, in which case each item in the list is processed. If the value is a list then you must provide the separator. If no separator is provided or the separator is the empty string then the value is treated as being a single value, not a list. The articles are those used by calibre to generate the title_sort.

swap_around_comma

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

swap_around_comma(value) -- given a value of the form B, A, return A B. This is most useful for converting names in LN, FN format to FN LN. If there is no comma in the value then the function returns the value unchanged.

test

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

test(value, text_if_not_empty, text_if_empty) -- return text_if_not_empty if the value is not empty, otherwise return text_if_empty.

transliterate

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

transliterate(value) -- Return a string in a latin alphabet formed by approximating the sound of the words in value. For example, if value is Фёдор Миха́йлович Достоевский this function returns Fiodor Mikhailovich Dostoievskii.

URL functions

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]+) -- this function is the easiest way to construct a query URL. It uses a path, the web site and page you want to query, and query_name, query_value pairs from which the query is built. In general, the query_value must be URL-encoded. With this function it is always encoded and spaces are always replaced with '+' signs.

At least one query_name, query_value pair must be provided.

Example: constructing a Wikipedia search URL for the author Niccolò Machiavelli:

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

returns

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

If you are writing a custom column book details URL template then use $item_name or field('item_name') to obtain the value of the field that was clicked on. Example: if Niccolò Machiavelli was clicked then you can construct the URL using:

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

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

make_url_extended

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

make_url_extended(...) -- this function is similar to make_url() but gives you more control over the URL components. The components of a URL are

scheme:://authority/path?query string.

See Uniform Resource Locator on Wikipedia for more detail.

The function has two variants:

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

and

make_url_extended(scheme, authority, path, query_string)

This function returns a URL constructed from the scheme, authority, path, and either the query_string or a query string constructed from the query argument pairs. The authority can be empty, which is the case for calibre scheme URLs. You must supply either a query_string or at least one query_name, query_value pair. If you supply query_string and it is empty then the resulting URL will not have a query string section.

Example 1: constructing a Wikipedia search URL for the author Niccolò Machiavelli:

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

returns

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

See the query_string() function for an example using make_url_extended() with a query_string.

If you are writing a custom column book details URL template then use $item_name or field('item_name') to obtain the value of the field that was clicked on. Example: if Niccolò Machiavelli was clicked on then you can construct the URL using :

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

See also the functions make_url(), query_string() and 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().

to_hex

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

to_hex(val) -- returns the string val encoded into hex. This is useful when constructing calibre URLs.

urls_from_identifiers

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

urls_from_identifiers(identifiers, sort_results) -- given a comma-separated list of identifiers, where an identifier is a colon-separated pair of values (id_name:id_value), returns a comma-separated list of HTML URLs generated from the identifiers. The list not sorted if sort_results is 0 (character or number), otherwise it is sorted alphabetically by the identifier name. The URLs are generated in the same way as the built-in identifiers column when shown in Book Details.

その他の文字

arguments

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

arguments(id[=expression] [, id[=expression]]*) -- Used in a stored template to retrieve the arguments passed in the call. It both declares and initializes local variables with the supplied names, the id``s, making them effectively parameters. The variables are positional; they get the value of the argument given in the call in the same position. If the corresponding argument is not provided in the call then ``arguments() assigns that variable the provided default value. If there is no default value then the variable is set to the empty string.

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]]*) -- Retrieves "global variables" that can be passed into the formatter. The name id is the name of the global variable. It both declares and initializes local variables with the names of the global variables passed in the id parameters. If the corresponding variable is not provided in the globals then it assigns that variable the provided default value. If there is no default value then the variable is set to the empty string.

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]]*) -- Sets globalvariables that can be passed into the formatter. The globals are given the name of the id passed in. The value of the id is used unless an expression is provided.

算術

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) -- returns x - y. Throws an exception if either x or y are not numbers. This function can usually be replaced by the - operator.

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',
))

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