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.

Arithmetic

add(x [, y]*)

class calibre.utils.formatter_functions.BuiltinAdd[broncode]

add(x [, y]*) – returns the sum of its arguments. Throws an exception if an argument is not a number. This function can often be replaced with the + operator.

ceiling(x)

class calibre.utils.formatter_functions.BuiltinCeiling[broncode]

ceiling(x) – returns the smallest integer greater than or equal to x. Throws an exception if x is not a number.

divide(x, y)

class calibre.utils.formatter_functions.BuiltinDivide[broncode]

divide(x, y) – returns x / y. Throws an exception if either x or y are not numbers. This function can often be replaced with the / operator.

floor(x)

class calibre.utils.formatter_functions.BuiltinFloor[broncode]

floor(x) – returns the largest integer less than or equal to x. Throws an exception if x is not a number.

fractional_part(x)

class calibre.utils.formatter_functions.BuiltinFractionalPart[broncode]

fractional_part(x) – returns the value after the decimal point. For example, fractional_part(3.14) returns 0.14. Throws an exception if x is not a number.

mod(x)

class calibre.utils.formatter_functions.BuiltinMod[broncode]

mod(x) – returns floor(remainder of x / y). Throws an exception if either x or y is not a number.

multiply(x [, y]*)

class calibre.utils.formatter_functions.BuiltinMultiply[broncode]

multiply(x [, y]*) – returns the product of its arguments. Throws an exception if any argument is not a number. This function can often be replaced with the * operator.

round(x)

class calibre.utils.formatter_functions.BuiltinRound[broncode]

round(x) – returns the nearest integer to x. Throws an exception if x is not a number.

subtract(x, y)

class calibre.utils.formatter_functions.BuiltinSubtract[broncode]

subtract(x, y) – returns x - y. Throws an exception if either x or y are not numbers. This function can often be replaced with the - operator.

Boolean

and(value [, value]*)

class calibre.utils.formatter_functions.BuiltinAnd[broncode]

and(value [, value]*) – returns the string “1” if all values are not empty, otherwise returns the empty string. This function works well with test or first_non_empty. You can have as many values as you want. In many cases the && operator can replace this function.

not(value)

class calibre.utils.formatter_functions.BuiltinNot[broncode]

not(value) – returns the string “1” if the value is empty, otherwise returns the empty string. This function works well with test or first_non_empty. In many cases the ! operator can replace this function.

or(value [, value]*)

class calibre.utils.formatter_functions.BuiltinOr[broncode]

or(value [, value]*) – returns the string “1” if any value is not empty, otherwise returns the empty string. This function works well with test or first_non_empty. You can have as many values as you want. In many cases the || operator can replace this function.

Date functions

date_arithmetic(date, calc_spec, fmt)

class calibre.utils.formatter_functions.BuiltinDateArithmetic[broncode]

date_arithmetic(date, calc_spec, fmt) – Calculate a new date from ‘date’ 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(datum1, datum2)

class calibre.utils.formatter_functions.BuiltinDaysBetween[broncode]

days_between(datum1, datum2) – geeft het aantal dagen tussen datum1 en datum2 terug. Het aantal is positief als datum1 groter is dan datum2, anders negatief. Als ofwel datum1 ofwel datum2 geen datum is, wordt een lege string terug gegeven.

today()

class calibre.utils.formatter_functions.BuiltinToday[broncode]

today() – geeft een datumstring voor vandaag. Deze waarde is gemaakt voor gebruik in de format_date of days_between, maar kan worden aangepast in iedere andere string. De datum is in ISO-formaat.

Formatting values

finish_formatting(val, fmt, prefix, suffix)

class calibre.utils.formatter_functions.BuiltinFinishFormatting[broncode]

finish_formatting(val, fmt, prefix, suffix) – toepassing van formaat, voor- en achtervoegsel op een waarde op dezelfde manier als in een sjabloon zoals`{series_index:05.2f| - |- }`. Bijvoorbeeld, het volgende programma produceert dezelfde uitvoer als bovenstaand sjabloon: programma: finish_formatting(field(“series_index”), “05.2f”, “ - “, “ - “)

format_date(val, format_string)

class calibre.utils.formatter_functions.BuiltinFormatDate[broncode]

format_date(val, format_string) – format the value, which must be a date, using the format_string, returning a string. 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: the date as a floating point number from_number[:fmt]: format the timestamp using fmt if present otherwise iso

format_date_field(field_name, format_string)

class calibre.utils.formatter_functions.BuiltinFormatDateField[broncode]

format_date_field(field_name, format_string) – format the value in the field ‘field_name’, which must be the lookup name of 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 can’t be used for computed dates or dates in string variables. Example: format_date_field(‘pubdate’, ‘yyyy.MM.dd’)

format_number(v, template)

class calibre.utils.formatter_functions.BuiltinFormatNumber[broncode]

format_number(v, template) – format the number v using a Python formatting template such as “{0:5.2f}” or “{0:,d}” or “${0:5,.2f}”. The field_name part of the template must be a 0 (zero) (the “{0:” in the above examples). See the template language and Python documentation for more examples. You can leave off the leading “{0:” and trailing “}” if the template contains only a format. Returns the empty string if formatting fails.

human_readable(w)

class calibre.utils.formatter_functions.BuiltinHumanReadable[broncode]

human_readable(w) – geeft een string terug die de waarde van getal w representeerd in KB, MB, GB, enz.

rating_to_stars(value, use_half_stars)

class calibre.utils.formatter_functions.BuiltinRatingToStars[broncode]

rating_to_stars(value, use_half_stars) – Returns the rating as string of star characters. The value is a number between 0 and 5. Set use_half_stars to 1 if you want half star characters for custom ratings columns that support non-integer ratings, for example 2.5.

urls_from_identifiers(identifiers, sort_results)

class calibre.utils.formatter_functions.BuiltinUrlsFromIdentifiers[broncode]

urls_from_identifiers(identifiers, sort_results) – given a comma-separated list of identifiers, where an identifier is a colon-separated pair of values (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.

Get values from metadata

annotation_count()

class calibre.utils.formatter_functions.BuiltinAnnotationCount[broncode]

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[broncode]

approximate_formats() – geeft een komma-gescheiden lijst van formaten die ooit zijn geassocieerd met het boek. Het is niet gegarandeerd dat de lijst correct is, alhoewel dat wel waarschijnlijk is. Deze functie kan worden aangeroepen in sjabloon programma modus met gebruik van het sjabloon “{:’approximate_formats()’}”. Merk op dat de namen van de formaten altijd in hoofdletters staan, zoals in EPUB. Deze functie werkt alleen in de GUI. als u deze waarden wilt gebruiken in bewaren-op-schijf of verzenden-naar-toestel sjablonen dan moet een aangepaste “Kolom gebouwd van andere kolommen” gemaakt worden, met gebruik van de functies in dat kolomsjabloon en waarde van die kolom gebruiken in uw bewaren/versturen sjablonen

author_sorts(waarde_afscheider)

class calibre.utils.formatter_functions.BuiltinAuthorSorts[broncode]

author_sorts(waarde_afscheider) – geeft een string terug die een lijst van auteur sorteer waarden bevat voor de auteurs van het boek. Het sorteren is diegene in de auteurs metadata (anders dan de auteur_sort bij boeken). De teruggegeven lijst heeft de vorm auteur sort 1 waarde_afscheider auteur sort 2 enz. De author_sort waarden in de lijst zijn in dezelfde volgorde als de auteurs van het boek. Indien u spaties wilt rond waarde_afscheider zet deze in de afscheider string

booksize()

class calibre.utils.formatter_functions.BuiltinBooksize[broncode]

booksize() – geeft de waarde van het grootte veld. Deze functie werkt alleen in de GUI. als u deze waarden wilt gebruiken in bewaren-op-schijf of verzenden-naar-toestel sjablonen dan moet een aangepaste “Kolom gebouwd van andere kolommen” gemaakt worden, met gebruik van de functies in dat kolomsjabloon en waarde van die kolom gebruiken in uw bewaren/versturen sjablonen

connected_device_name(storage_location)

class calibre.utils.formatter_functions.BuiltinConnectedDeviceName[broncode]

connected_device_name(storage_location) – if a device is connected then return the device name, otherwise return the empty string. Each storage location on a device can have a different name. The location names are ‘main’, ‘carda’ and ‘cardb’. This function works only in the GUI.

connected_device_uuid(storage_location)

class calibre.utils.formatter_functions.BuiltinConnectedDeviceUUID[broncode]

connected_device_uuid(storage_location) – 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 location names are ‘main’, ‘carda’ and ‘cardb’. This function works only in the GUI.

current_library_name()

class calibre.utils.formatter_functions.BuiltinCurrentLibraryName[broncode]

current_library_name() – Geeft de laatste naam in het pad van de huidige calibre bibliotheek. Deze functie kunt u aanroepen in sjabloon programmeer modus met “{:’current_library_name()’}”.

current_library_path()

class calibre.utils.formatter_functions.BuiltinCurrentLibraryPath[broncode]

current_library_path() – geef het pad naar de huidige calibre bibliotheek terug. Deze functie kan worden aangeroepen in sjabloon programmeer modus door het sjabloon “{:’current_library_path()’}” te gebruiken.

current_virtual_library_name()

class calibre.utils.formatter_functions.BuiltinCurrentVirtualLibraryName[broncode]

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

field(lookup_name)

class calibre.utils.formatter_functions.BuiltinField[broncode]

field(lookup_name) – returns the metadata field named by lookup_name

formats_modtimes(date_format)

class calibre.utils.formatter_functions.BuiltinFormatsModtimes[broncode]

formats_modtimes(date_format) – return a comma-separated list of colon-separated items representing modification times for the formats of a book. The date_format 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 mod time for a specific format. Note that format names are always uppercase, as in EPUB.

formats_paths()

class calibre.utils.formatter_functions.BuiltinFormatsPaths[broncode]

formats_paths() – retourneert een door komma’s gescheiden lijst van door dubbele punt gescheiden items die het volledige pad naar de formaten van een boek geven. U kunt gebruikmaken van de select-functie om het pad van een specifiek formaat op te vragen. Let erop dat formaatnamen altijd in hoofdletters zijn, zoals in EPUB.

formats_sizes()

class calibre.utils.formatter_functions.BuiltinFormatsSizes[broncode]

formats_sizes() – retourneert een door komma’s gescheiden lijst van door dubbele punten gescheiden items die de grootte van formaten van een boek in bytes weergeven. U kunt de select-functie gebruiken om de grootte van een specifiek formaat op te vragen. Let erop dat formaatnamen altijd in hoofdletters zijn, zoals EPUB.

has_cover()

class calibre.utils.formatter_functions.BuiltinHasCover[broncode]

has_cover() – Ja teruggeven als het boek een omslag heeft, anders een lege string

is_marked()

class calibre.utils.formatter_functions.BuiltinIsMarked[broncode]

is_marked() – check whether the book is ‘marked’ in calibre. If it is then return the value of the mark, either ‘true’ or the comma-separated list of named marks. Returns ‘’ if the book is not marked.

language_codes(language_strings)

class calibre.utils.formatter_functions.BuiltinLanguageCodes[broncode]

language_codes(language_strings) – geeft de taalcodes terug voor de string die is meegegeven in lang_strings. De strings moeten in de huidig gebruikte vertaling worden ingevoerd. Lang_strings is een kommagescheiden lijst.

language_strings(lang_codes, vertaling)

class calibre.utils.formatter_functions.BuiltinLanguageStrings[broncode]

language_strings(lang_codes, vertaling) – geeft de strings voor de taalcode meegegeven in lang_codes. Indien vertaling nu is, wordt de string in het Engels terug gegeven. Als de vertaling niet nul is, geef de strings terug in de huidige vertaling. Lang_codes is een kommagescheiden lijst.

ondevice()

class calibre.utils.formatter_functions.BuiltinOndevice[broncode]

ondevice() – geeft Ja als ondevice is ingesteld, anders een lege tekenreeks. Deze functie werkt alleen in de GUI. als u deze waarden wilt gebruiken in bewaren-op-schijf of verzenden-naar-toestel sjablonen dan moet een aangepaste “Kolom gebouwd van andere kolommen” gemaakt worden, met gebruik van de functies in dat kolomsjabloon en waarde van die kolom gebruiken in uw bewaren/versturen sjablonen

raw_field(lookup_name [, optional_default])

class calibre.utils.formatter_functions.BuiltinRawField[broncode]

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 ‘default’ if the field is undefined (‘None’).

raw_list(lookup_name, separator)

class calibre.utils.formatter_functions.BuiltinRawList[broncode]

raw_list(lookup_name, separator) – returns the metadata list named by lookup_name without applying any formatting or sorting and with items separated by separator.

series_sort()

class calibre.utils.formatter_functions.BuiltinSeriesSort[broncode]

series_sort() – de reekssorteerwaarde teruggeven

user_categories()

class calibre.utils.formatter_functions.BuiltinUserCategories[broncode]

user_categories() – geeft een komma-gescheiden lijst van gebruikers categorieën waarin dit boek voorkomt. Deze functie werkt alleen in de GUI. als u deze waarden wilt gebruiken in bewaren-op-schijf of verzenden-naar-toestel sjablonen dan moet een aangepaste “Kolom gebouwd van andere kolommen” gemaakt worden, met gebruik van de functies in dat kolomsjabloon en waarde van die kolom gebruiken in uw bewaren/versturen sjablonen

virtual_libraries()

class calibre.utils.formatter_functions.BuiltinVirtualLibraries[broncode]

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

If-then-else

check_yes_no(field_name, is_undefined, is_false, is_true)

class calibre.utils.formatter_functions.BuiltinCheckYesNo[broncode]

check_yes_no(field_name, is_undefined, is_false, is_true) – checks the value of the yes/no field named by the lookup key field_name for a value specified by the parameters, returning “yes” if a match is found, otherwise returning an 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 undefined (neither True nor False) or True. More than one of is_undefined, is_false, or is_true can be set to 1. This function is usually used by the test() or is_empty() functions.

contains(val, pattern, text if match, text if not match)

class calibre.utils.formatter_functions.BuiltinContains[broncode]

contains(val, pattern, text if match, text if not match) – checks if val contains matches for the regular expression pattern. Returns text if match if matches are found, otherwise it returns text if no match

field_exists(field_name)

class calibre.utils.formatter_functions.BuiltinFieldExists[broncode]

field_exists(field_name) – checks if a field (column) named field_name exists, returning ‘1’ if so and ‘’ if not.

ifempty(waarde, tekst indien leeg)

class calibre.utils.formatter_functions.BuiltinIfempty[broncode]

ifempty(waarde, tekst indien leeg) – geeft waarde terug als het veld niet leeg is, anders ‘tekst indien leeg’

test(val, text if not empty, text if empty)

class calibre.utils.formatter_functions.BuiltinTest[broncode]

test(val, text if not empty, text if empty) – return text if not empty if val is not empty, otherwise return text if empty

Iterating over values

first_non_empty(value [, value]*)

class calibre.utils.formatter_functions.BuiltinFirstNonEmpty[broncode]

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(val, [pattern, field,]+ else_field)

class calibre.utils.formatter_functions.BuiltinLookup[broncode]

lookup(val, [pattern, field,]+ else_field) – like switch, except the arguments are field (metadata) names, not text. The value of the appropriate field will be fetched and used. Note that because composite columns are fields, you can use this function in one composite field to use the value of some other composite field. This is extremely useful when constructing variable save paths

switch(val, [pattern, value,]+ else_value)

class calibre.utils.formatter_functions.BuiltinSwitch[broncode]

switch(val, [pattern, value,]+ else_value) – for each pattern, value pair, checks if val matches the regular expression pattern and if so, returns that value. If no pattern matches, then else_value is returned. You can have as many pattern, value pairs as you want

switch_if([test_expression, value_expression,]+ else_expression)

class calibre.utils.formatter_functions.BuiltinSwitchIf[broncode]

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(val, id_name [, found_val, not_found_val])

class calibre.utils.formatter_functions.BuiltinIdentifierInList[broncode]

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.

in_list(val, separator, [ pattern, found_val, ]+ not_found_val)

class calibre.utils.formatter_functions.BuiltinInList[broncode]

in_list(val, separator, [ pattern, found_val, ]+ not_found_val) – treating val as a list of items separated by separator, if the pattern matches any of the list values then return found_val.If the pattern matches no list value then return not_found_val. The pattern and found_value pairs can be repeated as many times as desired. The patterns are checked in order. The found_val for the first match is returned. Aliases: in_list(), list_contains()

list_item(waarde, index, scheiding)

class calibre.utils.formatter_functions.BuiltinListitem[broncode]

list_item(waarde, index, scheiding) – verwerk de waarde als een lijst van items gescheiden door ‘scheiding’ en geef het ‘index’de item terug. Het eerste item heeft index nul. Het laatste item kan worden teruggegeven door gebruik te maken van list_item(-1,scheiding). Als het item niet in de lijst zit zal een lege waarde worden terug gegeven. De scheiding heeft de zelfde functie als in de count functie.

select(val, key)

class calibre.utils.formatter_functions.BuiltinSelect[broncode]

select(val, key) – interpret the value as a comma-separated list of items, with the items being “id:value”. Find the pair with the id equal to key, and return the corresponding value. Returns the empty string if no match is found.

str_in_list(val, separator, [string, found_val, ]+ not_found_val)

class calibre.utils.formatter_functions.BuiltinStrInList[broncode]

str_in_list(val, separator, [string, found_val, ]+ not_found_val) – treating val as a list of items separated by separator, if the string matches any of the list values then return found_val.If the string matches no list value then return not_found_val. The comparison is exact match (not contains) and is case insensitive. The string and found_value pairs can be repeated as many times as desired. The patterns are checked in order. The found_val for the first match is returned.

List manipulation

count(val, separator)

class calibre.utils.formatter_functions.BuiltinCount[broncode]

count(val, separator) – interprets the value as a list of items separated by separator, returning the number of items in the list. Most lists use a comma as the separator, but authors uses an ampersand. Examples: {tags:count(,)}, {authors:count(&)}. Aliases: count(), list_count()

list_count_matching(list, pattern, separator)

class calibre.utils.formatter_functions.BuiltinListCountMatching[broncode]

list_count_matching(list, pattern, separator) – interprets ‘list’ 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(list1, list2, separator)

class calibre.utils.formatter_functions.BuiltinListDifference[broncode]

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(list1, sep1, list2, sep2, yes_val, no_val)

class calibre.utils.formatter_functions.BuiltinListEquals[broncode]

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(lijst1, lijst2, scheiding)

class calibre.utils.formatter_functions.BuiltinListIntersection[broncode]

list_intersection(lijst1, lijst2, scheiding) – geeft een lijst terug, gemaakt door uit lijst1 alle items te verwijderen die niet in lijst2 aanwezig zijn, niet hoofdlettergevoelig vergeleken. De items in lijst1 en lijst2 worden gescheiden door scheiding, zo ook de items in de teruggegeven lijst.

list_join(with_separator, list1, separator1 [, list2, separator2]*)

class calibre.utils.formatter_functions.BuiltinListJoin[broncode]

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, ‘&’)

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(bron_lijst, scheidingsteken, bevat_re, opt_vervang)

class calibre.utils.formatter_functions.BuiltinListRe[broncode]

list_re(bron_lijst, scheidingsteken, bevat_re, opt_vervang) – maakt een lijst door de bon_lijst te scheiden in items, gebruikmakend van het schiedingsteken. Voor ietder item in de lijst wordt gecontroleerd of het overeenkomst met bevat_re. Als dat zo is, wordt het toegevoerd aan de terug te geven lijst. Als opt_vervang geen lege string is, wordt deze vervanging toegepast voor het item wordt toegevoegd aan de teruggegeven lijst.

list_re_group(src_list, separator, include_re, search_re [, group_template]+)

class calibre.utils.formatter_functions.BuiltinListReGroup[broncode]

list_re_group(src_list, separator, include_re, search_re [, group_template]+) – Like list_re except replacements are not optional. It uses re_group(list_item, search_re, group_template, …) when doing the replacements on the resulting list.

list_remove_duplicates(list, separator)

class calibre.utils.formatter_functions.BuiltinListRemoveDuplicates[broncode]

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

list_sort(lijst, richting, scheiding)

class calibre.utils.formatter_functions.BuiltinListSort[broncode]

list_sort(lijst, richting, scheiding) – geef een lijst, gesorteerd zonder op hoofdletters te letten. Als richting nul is wordt de lijst oplopend gesorteerd, anders aflopend. De items in lijst worden gescheiden door scheiding, zo ook de items in de teruggegeven lijst.

list_split(list_val, sep, id_prefix)

class calibre.utils.formatter_functions.BuiltinListSplit[broncode]

list_split(list_val, sep, id_prefix) – splits the list_val into separate values using ‘sep’, then assigns the values to 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: split(‘one:two:foo’, ‘:’, ‘var’) is equivalent to var_0 = ‘one’; var_1 = ‘two’; var_2 = ‘foo’.

list_union(list1, list2, separator)

class calibre.utils.formatter_functions.BuiltinListUnion[broncode]

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: list_union(), merge_lists()

range(start, stop, step, limit)

class calibre.utils.formatter_functions.BuiltinRange[broncode]

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 are 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(val, start_index, end_index)

class calibre.utils.formatter_functions.BuiltinSubitems[broncode]

subitems(val, start_index, end_index) – Deze functie wordt gebruikt om lijsten van items zoals genres op te delen. Het interpreteert de waarde als een door komma’s gescheiden lijst met items, waarbij elk item een door punten gescheiden lijst is. Geeft een nieuwe lijst door eerst alle met punten gescheiden items te vinden, vervolgens voor elk item de waarde van de start_index tot end_index componenten te extraheren, en dan de resultaten wederom terug te combineren. De eerste component in een punt gescheiden lijst heeft een index van nul. Als een index negatief is, dan telt het vanaf het einde van de lijst. Als speciaal geval wordt een end_index van nul verondersteld de lengte van de lijst te zijn. Voorbeeld met gebruik van de basis sjabloon mode en uitgaande van een #genre waarde van “A.B.C”: {#genre:subitems(0,1)} retourneert “A”. {#genre:subitems(0,2)} retourneert “A.B”. {#genre:subitems(1,0)} retourneert “B.C”. Uitgaande van een #genre waarde van “A.B.C, D.E.F”, {#genre:subitems(0,1)} retourneert “A, D”. {#genre:subitems(0,2)} retourneert “A.B, D.E”

sublist(val, start_index, end_index, separator)

class calibre.utils.formatter_functions.BuiltinSublist[broncode]

sublist(val, start_index, end_index, separator) – interpret the value as a list of items separated by separator, returning a new list made from the start_index to the end_index item. 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 using basic template mode and 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”.

Other

arguments(id[=expression] [, id[=expression]]*)

class calibre.utils.formatter_functions.BuiltinArguments[broncode]

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, effectively parameters. The variables are positional; they get the value of the parameter given in the call in the same position. If the corresponding parameter 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(id, val)

class calibre.utils.formatter_functions.BuiltinAssign[broncode]

assign(id, val) – assigns val to id, then returns val. id must be an identifier, not an expression. This function can often be replaced with the = operator.

globals(id[=expression] [, id[=expression]]*)

class calibre.utils.formatter_functions.BuiltinGlobals[broncode]

globals(id[=expression] [, id[=expression]]*) – Retrieves “global variables” that can be passed into the formatter. It both declares and initializes local variables with the names of the global variables passed in. If the corresponding variable is not provided in the passed-in 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.

Recursion

eval(template)

class calibre.utils.formatter_functions.BuiltinEval[broncode]

eval(template) – evalueert het sjabloon, geeft lokale variabelen door (die ‘assign’ed zijn) in plaats van de metadata van het boek. Hierdoor kan met behulp van de sjabloon processor complexe resultaten geconstrueerd worden van lokale variabelen. Omdat de { en } karakters speciaal zijn, dient u [[ voor het { karakter en ]] voor het } karakter te gebruiken; deze worden automatisch omgezet. Merk ook op dat voor- en achtervoegsels (de |prefix|suffix syntaxis) niet gebruikt kunnen worden in het argument voor deze functie bij gebruik in sjabloon programmeer modus.

template(x)

class calibre.utils.formatter_functions.BuiltinTemplate[broncode]

template(x) – evalueert x als sjabloon. De evaluatie gebeurt in haar eigen samenhang, hetgeen betekent dat variabelen niet gedeeld worden tussen de aanroeper van de functie en de sjabloon evaluatie. Omdat de { en } karakters speciaal zijn, moet u [[ voor het { karakter en ]] voor het } karakter gebruiken; zij worden automatisch omgezet. Bijvoorbeeld, template(‘[[title_sort]]’) evalueert het sjabloon {title_sort} en geeft haar waarde terug. Merk op dat ook voorvoegsels en achtervoegsels (de |prefix|suffix syntaxis) niet gebruikt kunnen worden in het meegegeven argument naar deze functie wanneer u de sjabloon programmeer modus gebruikt.

Relational

cmp(x, y, lt, eq, gt)

class calibre.utils.formatter_functions.BuiltinCmp[broncode]

cmp(x, y, lt, eq, gt) – compares x and y after converting both to numbers. Returns lt if x < y. Returns eq if x == y. Otherwise returns gt. In many cases the numeric comparison operators (>#, <#, ==# etc) can replace this function.

first_matching_cmp(val, [cmp1, result1,]+, else_result)

class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp[broncode]

first_matching_cmp(val, [cmp1, result1,]+, else_result) – compares “val < cmpN” in sequence, returning resultN for the first comparison that succeeds. Returns else_result if no comparison succeeds. Example: first_matching_cmp(10,5,”small”,10,”middle”,15,”large”,”giant”) returns “large”. The same example with a first value of 16 returns “giant”.

strcmp(x, y, lt, eq, gt)

class calibre.utils.formatter_functions.BuiltinStrcmp[broncode]

strcmp(x, y, lt, eq, gt) – does a case-insensitive comparison of x and y as strings. Returns lt if x < y. Returns eq if x == y. Otherwise returns gt. In many cases the lexical comparison operators (>, <, == etc) can replace this function.

strcmpcase(x, y, lt, eq, gt)

class calibre.utils.formatter_functions.BuiltinStrcmpcase[broncode]

strcmpcase(x, y, lt, eq, gt) – does a case-sensitive comparison of x and y as strings. Returns lt if x < y. Returns eq if x == y. Otherwise returns 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 case changes

capitalize(val)

class calibre.utils.formatter_functions.BuiltinCapitalize[broncode]

capitalize(val) – retourneert val met hoofdletters

lowercase(val)

class calibre.utils.formatter_functions.BuiltinLowercase[broncode]

lowercase(val) – retourneert val in kleine letters

titlecase(val)

class calibre.utils.formatter_functions.BuiltinTitlecase[broncode]

titlecase(val) – retourneert alles in val met beginhoofdletters

uppercase(val)

class calibre.utils.formatter_functions.BuiltinUppercase[broncode]

uppercase(val) – retourneert val in hoofdletters

String manipulation

character(character_name)

class calibre.utils.formatter_functions.BuiltinCharacter[broncode]

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

re(val, pattern, replacement)

class calibre.utils.formatter_functions.BuiltinRe[broncode]

re(val, pattern, replacement) – return val after applying the regular expression. All instances of pattern are replaced with replacement. As in all of calibre, these are Python-compatible regular expressions

re_group(val, pattern [, template_for_group]*)

class calibre.utils.formatter_functions.BuiltinReGroup[broncode]

re_group(val, pattern [, template_for_group]*) – return a string made by applying the regular expression pattern to the val and replacing each matched instance with the string computed by replacing each matched group by the value returned by the corresponding template. The original matched value for the group is available as $. In template program mode, like for the template and the eval functions, you use [[ for { and ]] for }. The following example in template program mode looks for series with more than one word and uppercases the first word: {series:’re_group($, “(S* )(.*)”, “[[$:uppercase()]]”, “[[$]]”)’}

shorten(val, left chars, middle text, right chars)

class calibre.utils.formatter_functions.BuiltinShorten[broncode]

shorten(val, left chars, middle text, right chars) – Return a shortened version of val, consisting of left chars characters from the beginning of val, followed by middle text, followed by right chars characters from the end of the string. Left chars and right chars must be integers. For example, assume the title of the book is Ancient English Laws in the Times of Ivanhoe, and you want it to fit in a space of at most 15 characters. If you use {title:shorten(9,-,5)}, the result will be Ancient E-anhoe. If the field’s length is less than left chars + right chars + the length of middle text, then the field will be used intact. For example, the title The Dome would not be changed.

strcat(a [, b]*)

class calibre.utils.formatter_functions.BuiltinStrcat[broncode]

strcat(a [, b]*) – can take any number of arguments. Returns the string formed by concatenating all the arguments

strcat_max(max, string1 [, prefix2, string2]*)

class calibre.utils.formatter_functions.BuiltinStrcatMax[broncode]

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

strlen(a)

class calibre.utils.formatter_functions.BuiltinStrlen[broncode]

strlen(a) – Geeft de lengte van de string die als argument wordt meegegeven

substr(str, begin, eind)

class calibre.utils.formatter_functions.BuiltinSubstr[broncode]

substr(str, begin, eind) – geeft de tekens uit str die tussen begin en eind voorkomen. Het eerste teken in str is het 0-de teken. Als einde negatief is betekend dit ‘tot zoveel teken vanaf rechts’. Als einde nul is betekend dit het laatste teken. Bijvoorbeeld: substr(‘12345’, 1, 0) geeft ‘2345’, en substr(‘12345’, 1, -1) geeft ‘234’.

swap_around_articles(val, separator)

class calibre.utils.formatter_functions.BuiltinSwapAroundArticles[broncode]

swap_around_articles(val, separator) – returns the val with articles moved to the end. The value can be a list, in which case each member of the list is processed. If the value is a list then you must provide the list value separator. If no separator is provided then the value is treated as being a single value, not a list.

swap_around_comma(waarde)

class calibre.utils.formatter_functions.BuiltinSwapAroundComma[broncode]

swap_around_comma(waarde) – gegeven een waarde in de vorm “B, A”, wordt “A B” terug gegeven. Dit is heel nuttig voor het omzetten van namen in de vorm AN, VN naar VN AN. Als er geen komma is, wordt de waarde onveranderd teruggegeven

to_hex(val)

class calibre.utils.formatter_functions.BuiltinToHex[broncode]

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

transliterate(a)

class calibre.utils.formatter_functions.BuiltinTransliterate[broncode]

transliterate(a) – Retourneert een regel in een Latijns alfabet gevormd door de benadering van de klank van de woorden in de bron-regel. Bij voorbeeld, wanneer de bron “Фёдор Миха́йлович Достоевский” is, de functie retourneert “Fiodor Mikhailovich Dostoievskii”.

Template database functions

book_count(query, use_vl)

class calibre.utils.formatter_functions.BuiltinBookCount[broncode]

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 can be used only in the GUI.

book_values(column, query, sep, use_vl)

class calibre.utils.formatter_functions.BuiltinBookValues[broncode]

book_values(column, query, sep, use_vl) – returns a list of the values contained in the column “column”, separated by “sep”, in the books found by searching for “query”. If use_vl is 0 (zero) then virtual libraries are ignored. This function can be used only in the GUI.

extra_file_modtime(file_name, format_string)

class calibre.utils.formatter_functions.BuiltinExtraFileModtime[broncode]

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.0. The modtime is formatted according to ‘format_string’ (see format_date()). If ‘format_string’ is empty, returns the modtime as the floating point number of seconds since the epoch. The epoch is OS dependent. This function can be used only in the GUI.

extra_file_names(sep [, pattern])

class calibre.utils.formatter_functions.BuiltinExtraFileNames[broncode]

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. This function can be used only in the GUI.

extra_file_size(file_name)

class calibre.utils.formatter_functions.BuiltinExtraFileSize[broncode]

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.This function can be used only in the GUI.

get_note(field_name, field_value, plain_text)

class calibre.utils.formatter_functions.BuiltinGetNote[broncode]

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: get_note(‘tags’, ‘Fiction’, ‘’) returns the HTML of the note attached to the tag ‘Fiction’.

has_extra_files([pattern])

class calibre.utils.formatter_functions.BuiltinHasExtraFiles[broncode]

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. This function can be used only in the GUI.

has_note(field_name, field_value)

class calibre.utils.formatter_functions.BuiltinHasNote[broncode]

has_note(field_name, field_value) – return ‘1’ if the value ‘field_value’ in the field ‘field_name’ has an attached note, ‘’ otherwise. Example: has_note(‘tags’, ‘Fiction’) returns ‘1’ if the tag ‘fiction’ has an attached note, ‘’ otherwise.

other

is_dark_mode()

class calibre.utils.formatter_functions.BuiltinIsDarkMode[broncode]

is_dark_mode() – Returns ‘1’ if calibre is running in dark mode, ‘’ (the empty string) otherwise. This function can be used in advanced color and icon rules to choose different colors/icons according to the mode. Example: if is_dark_mode() then ‘dark.png’ else ‘light.png’ fi

set_globals(id[=expression] [, id[=expression]]*)

class calibre.utils.formatter_functions.BuiltinSetGlobals[broncode]

set_globals(id[=expression] [, id[=expression]]*) – Sets “global variables” 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.

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=('Onbekend',), other=None, template_cache=None, formatter=None)[broncode]

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)[broncode]

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>>)[broncode]

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()[broncode]

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)[broncode]

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

set_identifier(typ, val)[broncode]

If val is empty, deletes identifier of type typ

standard_field_keys()[broncode]

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

custom_field_keys()[broncode]

return a list of the custom fields in this book

all_field_keys()[broncode]

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

metadata_for_field(key)[broncode]

return metadata describing a standard or custom field.

all_non_none_fields()[broncode]

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

get_standard_metadata(field, make_copy)[broncode]

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)[broncode]

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

get_all_user_metadata(make_copy)[broncode]

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

get_user_metadata(field, make_copy)[broncode]

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)[broncode]

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

set_user_metadata(field, metadata)[broncode]

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

remove_stale_user_metadata(other_mi)[broncode]

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)[broncode]

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)[broncode]

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)[broncode]

Returns the tuple (display_name, formatted_value)

to_html()[broncode]

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