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.

Alteração de maiúsculas/minúsculas

capitalize

class calibre.utils.formatter_functions.BuiltinCapitalize[código fonte]

capitalize(value) – devolve o valor de value com a primeira letra em maísuculas e as restantes em minúsculas.

lowercase

class calibre.utils.formatter_functions.BuiltinLowercase[código fonte]

lowercase(value) – devolve o valor de value em minúsculas.

titlecase

class calibre.utils.formatter_functions.BuiltinTitlecase[código fonte]

titlecase(value) – devolve o valor de value no formato caixa de título.

uppercase

class calibre.utils.formatter_functions.BuiltinUppercase[código fonte]

uppercase(value) – devolve o valor de value em maísculas.

Aritmética

add

class calibre.utils.formatter_functions.BuiltinAdd[código fonte]

add(x [,y]*) — devolve a soma dos seus argumentos.. Lança uma exceção se um argumento não for um número. Esta função pode, muitas vezes, ser substituída pelo operador +.

ceiling

class calibre.utils.formatter_functions.BuiltinCeiling[código fonte]

ceiling(value) — devolve o menor número inteiro que seja maior que ou igual a value. Devolve uma exceção se value não for um número.

divide

class calibre.utils.formatter_functions.BuiltinDivide[código fonte]

divide(x, y) — devolve x - y. Devolve uma exceção se x ou y não forem números. Esta função pode, muitas vezes, ser substituída pelo operador / .

floor

class calibre.utils.formatter_functions.BuiltinFloor[código fonte]

floor(value) — devolve o maior número inteiro que seja menor que ou igual a value. Devolve uma exceção se value não for um número.

fractional_part

class calibre.utils.formatter_functions.BuiltinFractionalPart[código fonte]

fractional_part(value) — devolve o valor existente depois da casa decimal. Por exemplo, fractional_part(3.14) devolve 0.14. Lança uma exceção caso value não seja um número.

mod

class calibre.utils.formatter_functions.BuiltinMod[código fonte]

mod(value, y) — devolve o floor do remanascente de value / y. Devolve uma exceção se value ou y não forem números.

multiply

class calibre.utils.formatter_functions.BuiltinMultiply[código fonte]

multiply(x [,y]*) – devolve o produto de seus argumentos. Devolve uma exceção se um argumento não for um número. Esta função pode, muitas vezes, ser substituída pelo operador *.

round

class calibre.utils.formatter_functions.BuiltinRound[código fonte]

round(value) — devolve o número inteiro mais próximo de value. Devolve uma exceção se value não for um número.

subtract

class calibre.utils.formatter_functions.BuiltinSubtract[código fonte]

subtract(x, y) — devolve x - y. Devolve uma exceção se x ou y não forem números. Esta função pode, muitas vezes, ser substituída pelo operador - .

Booleano

and

class calibre.utils.formatter_functions.BuiltinAnd[código fonte]

and(value [, value]*) – returns the string '1' if all values are not empty, otherwise returns the empty string. You can have as many values as you want. In most cases you can use the && operator instead of this function. One reason not to replace and() with && is when short-circuiting can change the results because of side effects. For example, and(a='',b=5) will always do both assignments, where the && operator won’t do the second.

not

class calibre.utils.formatter_functions.BuiltinNot[código fonte]

not(value) – returns the string '1' if the value is empty, otherwise returns the empty string. This function can usually be replaced with the unary not (!) operator.

or

class calibre.utils.formatter_functions.BuiltinOr[código fonte]

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.

Formatação de valores

finish_formatting

class calibre.utils.formatter_functions.BuiltinFinishFormatting[código fonte]

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[código fonte]

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 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.

format_date_field

class calibre.utils.formatter_functions.BuiltinFormatDateField[código fonte]

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_number

class calibre.utils.formatter_functions.BuiltinFormatNumber[código fonte]

format_number(value, template) – interprets the value as a number and formats that number using a Python formatting template such as {0:5.2f} or {0:,d} or ${0:5,.2f}. The formatting template must begin with {0: and end with } as in the above examples. Exception: you can leave off the leading «{0:» and trailing «}» if the format template contains only a format. See the Template Language and the Python documentation for more examples. Returns the empty string if formatting fails.

human_readable

class calibre.utils.formatter_functions.BuiltinHumanReadable[código fonte]

human_readable(value) – expects the value to be a number and returns a string representing that number in KB, MB, GB, etc.

rating_to_stars

class calibre.utils.formatter_functions.BuiltinRatingToStars[código fonte]

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.

urls_from_identifiers

class calibre.utils.formatter_functions.BuiltinUrlsFromIdentifiers[código fonte]

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.

Funções de base de dados

book_count

class calibre.utils.formatter_functions.BuiltinBookCount[código fonte]

book_count(query, use_vl) – returns the count of books found by searching for query. If use_vl is 0 (zero) then virtual libraries are ignored. This function and its companion book_values() are particularly useful in template searches, supporting searches that combine information from many books such as looking for series with only one book. It cannot be used in composite columns unless the tweak allow_template_database_functions_in_composites is set to True. It can be used only in the GUI.

For example this template search uses this function and its companion to find all series with only one book:

  • Define a stored template (using Preferences → Advanced → Template functions) named series_only_one_book (the name is arbitrary). The template is:

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

    The first time the template runs (the first book checked) it stores the results of the database lookups in a global template variable named vals. These results are used to check subsequent books without redoing the lookups.

  • Use the stored template in a template search:

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

Using a stored template instead of putting the template into the search eliminates problems caused by the requirement to escape quotes in search expressions.

book_values

class calibre.utils.formatter_functions.BuiltinBookValues[código fonte]

book_values(column, query, sep, use_vl) – returns a list of the unique values contained in the column column (a lookup name), separated by sep, in the books found by searching for query. If use_vl is 0 (zero) then virtual libraries are ignored. This function and its companion book_count() are particularly useful in template searches, supporting searches that combine information from many books such as looking for series with only one book. It cannot be used in composite columns unless the tweak allow_template_database_functions_in_composites is set to True. It can be used only in the GUI.

extra_file_modtime

class calibre.utils.formatter_functions.BuiltinExtraFileModtime[código fonte]

extra_file_modtime(file_name, format_string) – returns the modification time of the extra file file_name in the book’s data/ folder if it exists, otherwise -1. The modtime is formatted according to format_string (see format_date() for details). If format_string is the empty string, returns the modtime as the floating point number of seconds since the epoch. See also the functions has_extra_files(), extra_file_names() and extra_file_size(). The epoch is OS dependent. This function can be used only in the GUI.

extra_file_names

class calibre.utils.formatter_functions.BuiltinExtraFileNames[código fonte]

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.

extra_file_size

class calibre.utils.formatter_functions.BuiltinExtraFileSize[código fonte]

extra_file_size(file_name) – returns the size in bytes of the extra file file_name in the book’s data/ folder if it exists, otherwise -1. See also the functions has_extra_files(), extra_file_names() and extra_file_modtime(). This function can be used only in the GUI.

get_note

class calibre.utils.formatter_functions.BuiltinGetNote[código fonte]

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)
    

has_extra_files

class calibre.utils.formatter_functions.BuiltinHasExtraFiles[código fonte]

has_extra_files([pattern]) – returns the count of extra files, otherwise “” (the empty string). If the optional parameter pattern (a regular expression) is supplied then the list is filtered to files that match pattern before the files are counted. The pattern match is case insensitive. See also the functions extra_file_names(), extra_file_size() and extra_file_modtime(). This function can be used only in the GUI.

has_note

class calibre.utils.formatter_functions.BuiltinHasNote[código fonte]

has_note(field_name, field_value). Check if a field has a note. This function has two variants:

  • if field_value is not '' (the empty string) return '1' if the value field_value in the field field_name has a note, otherwise ''.

    Example: has_note('tags', 'Fiction') returns '1' if the tag fiction has an attached note, otherwise ''.

  • If field_value is '' then return a list of values in field_name that have a note. If no item in the field has a note, return ''. This variant is useful for showing column icons if any value in the field has a note, rather than a specific value.

    Example: has_note('authors', '') returns a list of authors that have notes, or '' if no author has a note.

You can test if all the values in field_name have a note by comparing the list length of this function’s return value against the list length of the values in field_name. Example:

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

Funções de data

date_arithmetic

class calibre.utils.formatter_functions.BuiltinDateArithmetic[código fonte]

date_arithmetic(value, calc_spec, fmt) – Calculate a new date from value using calc_spec. Return the new date formatted according to optional fmt: if not supplied then the result will be in ISO format. The calc_spec is a string formed by concatenating pairs of vW (valueWhat) where v is a possibly-negative number and W is one of the following letters:

  • s: add v seconds to date

  • m: add v minutes to date

  • h: add v hours to date

  • d: add v days to date

  • w: add v weeks to date

  • y: add v years to date, where a year is 365 days.

Example: '1s3d-1m' will add 1 second, add 3 days, and subtract 1 minute from date.

days_between

class calibre.utils.formatter_functions.BuiltinDaysBetween[código fonte]

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.

today

class calibre.utils.formatter_functions.BuiltinToday[código fonte]

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.

Limitador de listas

identifier_in_list

class calibre.utils.formatter_functions.BuiltinIdentifierInList[código fonte]

identifier_in_list(val, id_name [, found_val, not_found_val]) – treat val as a list of identifiers separated by commas. An identifier has the format id_name:value. The id_name parameter is the id_name text to search for, either id_name or id_name:regexp. The first case matches if there is any identifier matching that id_name. The second case matches if id_name matches an identifier and the regexp matches the identifier’s value. If found_val and not_found_val are provided then if there is a match then return found_val, otherwise return not_found_val. If found_val and not_found_val are not provided then if there is a match then return the identifier:value pair, otherwise the empty string ('').

list_contains

class calibre.utils.formatter_functions.BuiltinInList[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

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.

Manipulação de listas

list_count

class calibre.utils.formatter_functions.BuiltinCount[código fonte]

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

list_count_field

class calibre.utils.formatter_functions.BuiltinFieldListCount[código fonte]

list_count_field(lookup_name)– returns the count of items in the field with the lookup name lookup_name. The field must be multi-valued such as authors or tags, otherwise the function raises an error. This function is much faster than list_count() because it operates directly on calibre data without converting it to a string first. Example: list_count_field('tags').

list_count_matching

class calibre.utils.formatter_functions.BuiltinListCountMatching[código fonte]

list_count_matching(value, pattern, separator) – interprets value as a list of items separated by separator, returning the number of items in the list that match the regular expression pattern.

Aliases: list_count_matching(), count_matching()

list_difference

class calibre.utils.formatter_functions.BuiltinListDifference[código fonte]

list_difference(list1, list2, separator) – return a list made by removing from list1 any item 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_equals

class calibre.utils.formatter_functions.BuiltinListEquals[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

list_split(list_val, sep, id_prefix) — separa list_val em valores separados usando sep, e então atribui os valores a variáveis nomeadas id_prefix_N onde N é a posição do valor na lista. O primeiro item tem uma posição 0 (zero). A função devolve o último elemento da lista.

Exemplo:

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[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

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»

Manipulação de sequências

character

class calibre.utils.formatter_functions.BuiltinCharacter[código fonte]

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.

check_yes_no

class calibre.utils.formatter_functions.BuiltinCheckYesNo[código fonte]

check_yes_no(field_name, is_undefined, is_false, is_true) – checks if the value of the yes/no field named by the lookup name field_name is one of the values specified by the parameters, returning 'Yes' if a match is found otherwise returning the empty string. Set the parameter is_undefined, is_false, or is_true to 1 (the number) to check that condition, otherwise set it to 0.

Example: check_yes_no("#bool", 1, 0, 1) returns 'Yes' if the yes/no field #bool is either True or undefined (neither True nor False).

More than one of is_undefined, is_false, or is_true can be set to 1.

contains

class calibre.utils.formatter_functions.BuiltinContains[código fonte]

contains(value, pattern, text_if_match, text_if_not_match) – verifica se o valor é correspondido pela expressão regular pattern. Devolve text_if_match se o padrão corresponde ao valor, caso contrário devolve text_if_not_match.

field_exists

class calibre.utils.formatter_functions.BuiltinFieldExists[código fonte]

field_exists(lookup_name) – checks if a field (column) with the lookup name lookup_name exists, returning '1' if so and the empty string if not.

ifempty

class calibre.utils.formatter_functions.BuiltinIfempty[código fonte]

ifempty(value, text_if_empty) – if the value is not empty then return that value, otherwise return text_if_empty.

re

class calibre.utils.formatter_functions.BuiltinRe[código fonte]

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[código fonte]

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[código fonte]

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[código fonte]

strcat(a [, b]*) — devolve uma sequência formada pela concatenação dos seus argumentos. Pode receber qualquer número de argumentos. Esta função pode, muitas vezes, ser substituída pelo operador &.

strcat_max

class calibre.utils.formatter_functions.BuiltinStrcatMax[código fonte]

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[código fonte]

strlen(value) – Devolve o comprimento da sequência value.

substr

class calibre.utils.formatter_functions.BuiltinSubstr[código fonte]

substr(value, start, end) – devolve o start’ésimo até o end’ésimo caracteres de value. O primeiro carácter em value é o zero’ésimo caractere. Se end for negativo, então indica esse número de caracteres contados da direita. Se end for zero, então indica o último carácter. Por exemplo, substr('12345', 1, 0) devolve '2345', e substr('12345', 1, -1) devolve '234'.

swap_around_articles

class calibre.utils.formatter_functions.BuiltinSwapAroundArticles[código fonte]

swap_around_articles(value, separator) – returns the value with articles moved to the end. 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 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[código fonte]

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[código fonte]

test(value, text_if_not_empty, text_if_empty) — devolve text_if_not_empty` se o valor não estiver vazio, caso contrário devolve ``text_if_empty`.

to_hex

class calibre.utils.formatter_functions.BuiltinToHex[código fonte]

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

transliterate

class calibre.utils.formatter_functions.BuiltinTransliterate[código fonte]

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.

Obter valores dos metadados

annotation_count

class calibre.utils.formatter_functions.BuiltinAnnotationCount[código fonte]

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

approximate_formats

class calibre.utils.formatter_functions.BuiltinApproximateFormats[código fonte]

approximate_formats() – return a comma-separated list of formats associated with the book. Because the list comes from calibre’s database instead of the file system, there is no guarantee that the list is correct, although it probably is. Note that resulting format names are always uppercase, as in EPUB. The approximate_formats() function is much faster than the formats_... functions.

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.

author_sorts

class calibre.utils.formatter_functions.BuiltinAuthorSorts[código fonte]

author_sorts(val_separator) – returns a string containing a list of author’s sort values for the authors of the book. The sort is the one in the author metadata information, which can be different from the author_sort in books. The returned list has the form author sort 1 val_separator author sort 2 etc. with no added spaces. The author sort values in this list are in the same order as the authors of the book. If you want spaces around val_separator then include them in the val_separator string.

booksize

class calibre.utils.formatter_functions.BuiltinBooksize[código fonte]

booksize() – returns the value of the calibre size field. Returns “” if the book has no formats.

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

connected_device_name

class calibre.utils.formatter_functions.BuiltinConnectedDeviceName[código fonte]

connected_device_name(storage_location_key) – if a device is connected then return the device name, otherwise return the empty string. Each storage location on a device has its own device name. The storage_location_key names are 'main', 'carda' and 'cardb'. This function works only in the GUI.

connected_device_uuid

class calibre.utils.formatter_functions.BuiltinConnectedDeviceUUID[código fonte]

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.

current_library_name

class calibre.utils.formatter_functions.BuiltinCurrentLibraryName[código fonte]

current_library_name() – devolve último nome no caminho para a biblioteca atual do Calibre.

current_library_path

class calibre.utils.formatter_functions.BuiltinCurrentLibraryPath[código fonte]

current_library_path() – devolve caminho completo para a biblioteca atual do Calibre.

current_virtual_library_name

class calibre.utils.formatter_functions.BuiltinCurrentVirtualLibraryName[código fonte]

current_virtual_library_name() – return the name of the current virtual library if there is one, otherwise the empty string. Library name case is preserved. Example:

program: current_virtual_library_name()

This function works only in the GUI.

field

class calibre.utils.formatter_functions.BuiltinField[código fonte]

field(lookup_name) – devolve o valor do campo de metadados com o nome de pesquisa lookup_name. O prefixo $ pode ser usado em vez da função, como em $tags.

formats_modtimes

class calibre.utils.formatter_functions.BuiltinFormatsModtimes[código fonte]

formats_modtimes(date_format_string) – return a comma-separated list of colon-separated items FMT:DATE representing modification times for the formats of a book. The date_format_string parameter specifies how the date is to be formatted. See the format_date() function for details. You can use the select() function to get the modification time for a specific format. Note that format names are always uppercase, as in EPUB.

formats_paths

class calibre.utils.formatter_functions.BuiltinFormatsPaths[código fonte]

formats_paths() – return a comma-separated list of colon-separated items FMT:PATH giving the full path to the formats of a book. You can use the select() function to get the path for a specific format. Note that format names are always uppercase, as in EPUB.

formats_sizes

class calibre.utils.formatter_functions.BuiltinFormatsSizes[código fonte]

formats_sizes() – return a comma-separated list of colon-separated FMT:SIZE items giving the sizes of the formats of a book in bytes. You can use the select() function to get the size for a specific format. Note that format names are always uppercase, as in EPUB.

has_cover

class calibre.utils.formatter_functions.BuiltinHasCover[código fonte]

has_cover() – devolve 'Yes' se o livro possuir capa, caso contrário devolve uma expressão vazia.

is_marked

class calibre.utils.formatter_functions.BuiltinIsMarked[código fonte]

is_marked() – check whether the book is marked in calibre. If it is then return the value of the mark, either 'true' (lower case) or a comma-separated list of named marks. Returns '' (the empty string) if the book is not marked. This function works only in the GUI.

language_codes

class calibre.utils.formatter_functions.BuiltinLanguageCodes[código fonte]

language_codes(lang_strings) – return the language codes for the language names passed in lang_strings. The strings must be in the language of the current locale. lang_strings is a comma-separated list.

language_strings

class calibre.utils.formatter_functions.BuiltinLanguageStrings[código fonte]

language_strings(value, localize) – return the language names for the language codes (see here for names and codes) passed in value. Example: {languages:language_strings()}. If localize is zero, return the strings in English. If localize is not zero, return the strings in the language of the current locale. lang_codes is a comma-separated list.

ondevice

class calibre.utils.formatter_functions.BuiltinOndevice[código fonte]

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[código fonte]

raw_field(lookup_name [, optional_default]) – devolve o campo de metadados nomeado por lookup_name sem aplicar nenhuma formatação. Irá avaliar e devolver o segundo argumento opcional optional_default se o valor do campo estiver como indefinido (None). O prefixo $$ pode ser usado em vez da função, como em $$pubdate.

raw_list

class calibre.utils.formatter_functions.BuiltinRawList[código fonte]

raw_list(lookup_name, separator) — devolve a lista de metadados nomeada por lookup_name mas sem aplicar qualquer formatação ou ordenação e com itens separados por separator.

series_sort

class calibre.utils.formatter_functions.BuiltinSeriesSort[código fonte]

series_sort() — devolve o valor de ordenação da série.

user_categories

class calibre.utils.formatter_functions.BuiltinUserCategories[código fonte]

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[código fonte]

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.

Outro(s)

arguments

class calibre.utils.formatter_functions.BuiltinArguments[código fonte]

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[código fonte]

assign(id, val) — atribui value a id e depois devolve value. O id deve ser um identificador e não uma expressão. Esta função pode, muitas vezes, ser substituída pelo operador =

globals

class calibre.utils.formatter_functions.BuiltinGlobals[código fonte]

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[código fonte]

is_dark_mode() – devolve '1' se o Calibre estiver a ser executado em modo escuro, caso contário devolve '' (a sequência vazia). Esta função pode ser usada em regras avançadas de cores e ícones para escolher cores/ícones diferentes de acordo com o modo. Exemplo:

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

print

class calibre.utils.formatter_functions.BuiltinPrint[código fonte]

print(a [, b]*) — imprime os argumentos para a saída predefinida. A menos que vá iniciar o Calibre a partir da linha de comandos (calibre-debug -g), a saída irá parar a um buraco negro. A função print devlve sempre o primeiro argumento.

set_globals

class calibre.utils.formatter_functions.BuiltinSetGlobals[código fonte]

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.

Recorrência

eval

class calibre.utils.formatter_functions.BuiltinEval[código fonte]

eval(string) – avalia a sequência como um programa, passando as variáveis locais. Isto permite usar o processador de modelo para construir resultados complexos a partir de variáveis ​​locais. No Modo de programa por modelos, porque os caracteres { e } são interpretados antes que o modelo seja avaliado, deve usar [[ para o carácter { e ]] para o carácter }. Serão convertidos automaticamente. Note também que prefixos e sufixos (a sintaxe |prefix|suffix) não podem ser usados ​​no argumento para esta função ao usar o Modo de programa por modelos.

template

class calibre.utils.formatter_functions.BuiltinTemplate[código fonte]

template(x) – analisa x como um modelo.. A analise é feita em seu próprio contexto, o que significa que as variáveis não são partilhadas entre a chamador e a análise do modelo. Se não usar o modo de Programação geral, e porque os caracteres { e } são especiais, deve usar [[ para { e ]] para o carácter }. Serão convertidos automaticamente. Por exemplo, template(\'[[title_sort]]\') irá analisar o modelo {title_sort} e devolver o seu valor. Note também que prefixos e sufixos (a sintaxwe |prefix|suffix ) não podem ser usados no argumento para esta função ao usar o modo de Programação por modelos.

Relacional

cmp

class calibre.utils.formatter_functions.BuiltinCmp[código fonte]

cmp(value, y, lt, eq, gt) – compares value and y after converting both to numbers. Returns lt if value <# y, eq if value ==# y, otherwise gt. This function can usually be replaced with one of the numeric compare operators (==#, <#, >#, etc).

A mostrar a documentação em inglês devido ao erro FFML: Missing closing «`» for italics on line 2 in «cmp»

first_matching_cmp

class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp[código fonte]

first_matching_cmp(val, [ cmp, result, ]* else_result) — compara val < cmp em sequência, devolvendo o result associado para a primeira comparação com sucesso. Devolve else_result se não houver comparações com sucesso. Exemplo:

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

devolve "large". O mesmo exemplo, mas em que o primeiro valor seja 16, devolve "giant".

strcmp

class calibre.utils.formatter_functions.BuiltinStrcmp[código fonte]

strcmp(x, y, lt, eq, gt) — faz uma comparação lexical, não diferenciadora de maiúsculas, de x e y. Devolve lt se x < y. Devolve eq se x == y. Caso contrário devolve gt. Esta função pode ser substituída, em muitos casos, por um dos operadores de comparação lexical (==, >, <, etc.)

strcmpcase

class calibre.utils.formatter_functions.BuiltinStrcmpcase[código fonte]

strcmpcase(x, y, lt, eq, gt) — faz uma comparação lexical entre x e y com diferenciação entre maiúsculas e minúsculas. Devolve lt se x < y. Devolve eq se x == y. De contrário devolve gt. Nota: Este NÃO é o comportamento predefinido usado pelo Calibre, por exemplo, nos operadores de comparação léxical (==, >, <, etc.). Esta função pode causar resultados inesperados. Utilize strcmp() sempre que possível.

Repetir sobre valores:

first_non_empty

class calibre.utils.formatter_functions.BuiltinFirstNonEmpty[código fonte]

first_non_empty(value [, value]*) – returns the first value that is not empty. If all values are empty, then the empty string is returned. You can have as many values as you want.

lookup

class calibre.utils.formatter_functions.BuiltinLookup[código fonte]

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[código fonte]

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[código fonte]

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.

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=('Desconhecido',), other=None, template_cache=None, formatter=None)[código fonte]

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)[código fonte]

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>>)[código fonte]

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()[código fonte]

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)[código fonte]

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

set_identifier(typ, val)[código fonte]

If val is empty, deletes identifier of type typ

standard_field_keys()[código fonte]

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

custom_field_keys()[código fonte]

return a list of the custom fields in this book

all_field_keys()[código fonte]

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

metadata_for_field(key)[código fonte]

return metadata describing a standard or custom field.

all_non_none_fields()[código fonte]

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

get_standard_metadata(field, make_copy)[código fonte]

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)[código fonte]

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

get_all_user_metadata(make_copy)[código fonte]

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

get_user_metadata(field, make_copy)[código fonte]

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)[código fonte]

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

set_user_metadata(field, metadata)[código fonte]

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

remove_stale_user_metadata(other_mi)[código fonte]

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)[código fonte]

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)[código fonte]

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)[código fonte]

Returns the tuple (display_name, formatted_value)

to_html()[código fonte]

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