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

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

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

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

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

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

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

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

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

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

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

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

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

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

days_between(Datum1, Datum2) – gibt die Anzahl der Tage zwischen Datum1 und Datum2 zurück. Die Zahl ist positiv, falls Datum1 größer als Datum2 ist, andernfalls negativ. Falls Datum1 und/oder Datum2 keine Kalenderdaten sind, wird eine leere Zeichenkette zurückgegeben.

today()

class calibre.utils.formatter_functions.BuiltinToday[Quellcode]

today() – gibt eine Datumszeichenkette für den aktuellen Tag zurück. Dieser Wert ist für den Einsatz in den Funktionen „format_date“ oder „days_between“ gedacht, kann aber wie jede andere Zeichenkette verändert werden. Das Datum entspricht dem ISO-Format.

Formatting values

finish_formatting(Wert, Format, Präfix, Suffix)

class calibre.utils.formatter_functions.BuiltinFinishFormatting[Quellcode]

finish_formatting(Wert, Format, Präfix, Suffix) – wendet das Format, den Präfix und den Suffix auf einen Wert in der gleichen Weise an, wie in einer Vorlage wie {series_index:05.2f| - |- }. Beispielsweise bewirkt das folgende Programm die gleiche Ausgabe, wie die obige Vorlage: finish_formatting(field(„series_index“), „05.2f“, „ - „, „ - „)

format_date(val, format_string)

class calibre.utils.formatter_functions.BuiltinFormatDate[Quellcode]

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

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

format_number(v, template) – formatieren Sie die Zahl v mit Hilfe einer Python-Formatierungsvorlage wie „{0:5.2f}“ oder „{0:,d}“ oder „${0:5,.2f}“. Der field_name Teil des Templates muss eine 0 (Null) sein (das „{0:“ in den obigen Beispielen). Weitere Beispiele finden Sie in der Template-Sprache und in der Python-Dokumentation. Sie können das führende „{0:“ und das abschließende „}“ weglassen, wenn das Template nur ein Format enthält. Gibt die leere Zeichenkette zurück, wenn die Formatierung fehlschlägt.

human_readable(w)

class calibre.utils.formatter_functions.BuiltinHumanReadable[Quellcode]

human_readable(w) – gibt eine Zeichenkette zurück, die die Zahl w in KB, MB, GB etc. darstellt.

rating_to_stars(value, use_half_stars)

class calibre.utils.formatter_functions.BuiltinRatingToStars[Quellcode]

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

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

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

approximate_formats() – gibt eine kommagetrennte Liste von Formaten zurück, die zu einem bestimmten Zeitpunkt zu dem Buch gehörten. Es existiert keine Garantie, dass diese Liste korrekt ist, wahrscheinlich ist sie es allerdings. Diese Funktion kann im Vorlageprogrammmodus unter Verwendung der Vorlage „{program:‘approximate_formats()‘}“ aufgerufen werden. Beachten Sie, dass Formatnamen immer aus Großbuchstaben bestehen, wie z. B. in „EPUB“. Diese Funktion funktioniert nur in der grafischen Benutzeroberfläche. Falls Sie diese Werte in den Vorlagen für „Exportieren“ oder „Auf Gerät übertragen“ verwenden wollen, müssen eine benutzerdefinierte Spalte des Typs „Aus anderen Spalten aufgebaute Spalte“ erstellen, die Funktion in der Vorlage jener Spalte verwenden, und den Wert jener Spalte in Ihren Vorlagen für „Speichern“ und „Senden“ verwenden.

author_sorts(Wertetrennzeichen)

class calibre.utils.formatter_functions.BuiltinAuthorSorts[Quellcode]

author_sorts(Wertetrennzeichen) – gibt eine Zeichenkette zurück, die eine Liste von Autorensortierungswerten für die Autoren des Buchs enthält. Die Sortierung ist jene in den Autormetadaten (unterscheidet sich von der Autorensortierung in Büchern). Die zurückgegebene Liste besitzt die Form „Autorensortierung1 Wertetrennzeichen Autorensortierung2 …“ Die Autorensortierungswerte in dieser Liste besitzen die gleiche Reihenfolge wie die Autoren des Buches. Falls Sie Leerzeichen um das Wertetrennzeichen herum wollen, so schließen Sie diese in die Trennzeichen-Zeichenkette mit ein.

booksize()

class calibre.utils.formatter_functions.BuiltinBooksize[Quellcode]

booksize() – gibt den Wert des Größenfeldes zurück. Diese Funktion funktioniert nur in der grafischen Benutzeroberfläche. Falls Sie diesen Wert in den Vorlagen für „Exportieren“ oder „Auf Gerät übertragen“ verwenden wollen, müssen eine benutzerdefinierte Spalte des Typs „Aus anderen Spalten aufgebaute Spalte“ erstellen, die Funktion in der Vorlage jener Spalte verwenden, und den Wert jener Spalte in Ihren Vorlagen für „Speichern“ und „Senden“ verwenden.

connected_device_name(storage_location)

class calibre.utils.formatter_functions.BuiltinConnectedDeviceName[Quellcode]

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

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

current_library_name() – gibt den letzten Namen im Pfad zur aktuellen Calibre-Bibliothek zurück. Diese Funktion kann im Vorlageprogrammmodus durch Verwendung der Vorlage „{:‘current_library_name()‘}“ aufgerufen werden.

current_library_path()

class calibre.utils.formatter_functions.BuiltinCurrentLibraryPath[Quellcode]

current_library_path() – gibt den Pfad zur aktuellen Calibe-Bibliothek zurück. Diese Funktion kann im Vorlageprogrammmodus durch Verwendung der Vorlage „{:‘current_library_path()‘}“ aufgerufen werden.

current_virtual_library_name()

class calibre.utils.formatter_functions.BuiltinCurrentVirtualLibraryName[Quellcode]

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

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

formats_modtimes(Datumsformat)

class calibre.utils.formatter_functions.BuiltinFormatsModtimes[Quellcode]

formats_modtimes(Datumsformat) – gibt eine kommagetrennte Liste von doppelpunktgetrennten Elementen zurück, welche die Änderungszeitpunkte für die Formate eines Buches darstellen. Der Parameter Datumsformat gibt die Formatierung des Datums an. Siehe die Funktion „format_date“ für Details. Sie können die Funktion „select“ verwenden, um den Änderungszeitpunkt für ein bestimmtes Format zu erhalten. Beachten Sie, dass Formatnamen immer aus Großbuchstaben bestehen, wie z. B. in „EPUB“.

formats_paths()

class calibre.utils.formatter_functions.BuiltinFormatsPaths[Quellcode]

formats_paths() – gibt eine kommagetrennte Liste von doppelpunktgetrennten Elementen zurück, welche den vollen Pfad zu den Formaten eines Buches darstellen. Sie können die Funktion „select“ verwenden, um den Pfad für ein bestimmtes Format zu erhalten. Beachten Sie, dass Formatnamen immer aus Großbuchstaben bestehen, wie z. B. in „EPUB“.

formats_sizes()

class calibre.utils.formatter_functions.BuiltinFormatsSizes[Quellcode]

formats_sizes() – gibt eine kommagetrennte Liste von doppelpunktgetrennten Elementen zurück, welche die Größen in Bytes der Formate eines Buches darstellen. Sie können die Funktion „select“ verwenden, um die Größe für ein bestimmtes Format zu erhalten. Beachten Sie, dass Formatnamen immer aus Großbuchstaben bestehen, wie z. B. in „EPUB“.

has_cover()

class calibre.utils.formatter_functions.BuiltinHasCover[Quellcode]

has_cover() – gibt „Yes“ zurück, falls das Buch ein Titelbild besitzt, andernfalls wird eine leere Zeichenkette zurückgegeben.

is_marked()

class calibre.utils.formatter_functions.BuiltinIsMarked[Quellcode]

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

class calibre.utils.formatter_functions.BuiltinLanguageCodes[Quellcode]

language_codes(Sprachzeichenketten) – gibt die Sprachcodes für die in Sprachzeichenketten übergebenen Zeichenketten zurück. Die Zeichenketten müssen der Sprache des aktuellen Gebietsschemas entsprechen. Sprachzeichenketten ist eine kommagetrennte Liste.

language_strings(Sprachcodes, lokalisieren)

class calibre.utils.formatter_functions.BuiltinLanguageStrings[Quellcode]

language_strings(Sprachcodes, lokalisieren) – gibt die Zeichenketten für die in Sprachcodes übergebenen Sprachcodes zurück. Falls lokalisieren gleich null ist, werden die Zeichenketten in Englisch zurückgegeben. Falls lokalisieren ungleich null ist, werden die Zeichenketten in der Sprache das aktuellen Gebietsschemas zurückgegeben. Sprachcodes ist eine kommagetrennte Liste.

ondevice()

class calibre.utils.formatter_functions.BuiltinOndevice[Quellcode]

ondevice() – gibt „Yes“ zurück, falls „ondevice“ gesetzt ist, andernfalls wird eine leere Zeichenkette zurückgegeben. Diese Funktion funktioniert nur in der grafischen Benutzeroberfläche. Falls Sie diesen Wert in den Vorlagen für „Exportieren“ oder „Auf Gerät übertragen“ verwenden wollen, müssen eine benutzerdefinierte Spalte des Typs „Aus anderen Spalten aufgebaute Spalte“ erstellen, die Funktion in der Vorlage jener Spalte verwenden, und den Wert jener Spalte in Ihren Vorlagen für „Speichern“ und „Senden“ verwenden.

raw_field(lookup_name [, optional_default])

class calibre.utils.formatter_functions.BuiltinRawField[Quellcode]

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

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

series_sort() – gibt den Seriensortierungswert zurück.

user_categories()

class calibre.utils.formatter_functions.BuiltinUserCategories[Quellcode]

user_categories() – gibt eine kommagetrennte Liste der Benutzerkategorien zurück, die dieses Buch enthalten. Diese Funktion funktioniert nur in der grafischen Benutzeroberfläche. Falls Sie diesen Wert in den Vorlagen für „Exportieren“ oder „Auf Gerät übertragen“ verwenden wollen, müssen eine benutzerdefinierte Spalte des Typs „Aus anderen Spalten aufgebaute Spalte“ erstellen, die Funktion in der Vorlage jener Spalte verwenden, und den Wert jener Spalte in Ihren Vorlagen für „Speichern“ und „Senden“ verwenden.

virtual_libraries()

class calibre.utils.formatter_functions.BuiltinVirtualLibraries[Quellcode]

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

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(Wert, Muster, Text_bei_Übereinstimmung, Text_bei_keiner_Übereinstimmung)

class calibre.utils.formatter_functions.BuiltinContains[Quellcode]

contains(Wert, Muster, Text_bei_Übereinstimmung, Text_bei_keiner_Übereinstimmung) – überprüft, ob Wert Übereinstimmungen mit dem regulären Ausdruck Muster enthält. Gibt Text_bei_Übereinstimmung zurück, falls Übereinstimmungen gefunden wurden, andernfalls wird Text_bei_keiner_Übereinstimmung zurückgegeben.

field_exists(field_name)

class calibre.utils.formatter_functions.BuiltinFieldExists[Quellcode]

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

ifempty(Wert, Text_falls_leer)

class calibre.utils.formatter_functions.BuiltinIfempty[Quellcode]

ifempty(Wert, Text_falls_leer) – gibt Wert zurück, falls Wert nicht leer ist, andernfalls wird Text_falls_leer zurückgegeben.

test(Wert, Text_falls_nicht_leer, Text_falls_leer)

class calibre.utils.formatter_functions.BuiltinTest[Quellcode]

test(Wert, Text_falls_nicht_leer, Text_falls_leer) – gibt Text_falls_nicht_leer zurück, falls Wert nicht leer ist, andernfalls Text_falls_leer.

Iterating over values

first_non_empty(value [, value]*)

class calibre.utils.formatter_functions.BuiltinFirstNonEmpty[Quellcode]

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

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

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

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

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

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(Wert, Index, Trennzeichen)

class calibre.utils.formatter_functions.BuiltinListitem[Quellcode]

list_item(Wert, Index, Trennzeichen) – interpretiert den Wert als eine durch Trennzeichen voneinander getrennte Liste von Elementen und gibt das index-te Element zurück. Das erste Element besitzt die Indexnummer null. Das letzte Element kann durch „list_item(-1,`Trennzeichen`)“ zurückgegeben werden. Falls sich das Element nicht in der Liste befindet, wird ein leerer Wert zurückgegeben. Das Trennzeichen hat die gleiche Bedeutung wie in der Funktion „count“.

select(val, key)

class calibre.utils.formatter_functions.BuiltinSelect[Quellcode]

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

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

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

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(Liste1, Liste2, Trennzeichen)

class calibre.utils.formatter_functions.BuiltinListDifference[Quellcode]

list_difference(Liste1, Liste2, Trennzeichen) – gibt eine Liste zurück, die durch Entfernen jedes Elements von Liste1, das in Liste2 gefunden wird, unter Verwendung eines von Groß-/Kleinschreibung unabhängigen Vergleichs erstellt wird. Die Elemente in Liste1 und Liste2 werden durch Trennzeichen voneinander getrennt, ebenso wie die Elemente der zurückgegebenen Liste.

list_equals(Liste1, Trennzeichen1, Liste2, Trennzeichen2, ja_Wert, nein_Wert)

class calibre.utils.formatter_functions.BuiltinListEquals[Quellcode]

list_equals(Liste1, Trennzeichen1, Liste2, Trennzeichen2, ja_Wert, nein_Wert) – gibt ja_Wert zurück, falls Liste1 und Liste2 die gleichen Elemente enthalten, andernfalls wird nein_Wert zurückgegeben. Die Elemente werden durch Aufteilen jeder Liste unter Verwendung des entsprechenden Trennzeichens (Trennzeichen1 oder Trennzeichen2) bestimmt. Die Reihenfolge der Elemente in den Listen ist dabei irrelevant. Der Vergleich ignoriert die Groß-/Kleinschreibung.

list_intersection(Liste1, Liste2, Trennzeichen)

class calibre.utils.formatter_functions.BuiltinListIntersection[Quellcode]

list_intersection(Liste1, Liste2, Trennzeichen) – gibt eine Liste zurück, die durch Entfernen jedes Elements von Liste1, das in Liste2 nicht gefunden wird, unter Verwendung eines von Groß-/Kleinschreibung unabhängigen Vergleichs erstellt wird. Die Elemente in Liste1 und Liste2 werden durch Trennzeichen voneinander getrennt, ebenso wie die Elemente der zurückgegebenen Liste.

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

class calibre.utils.formatter_functions.BuiltinListJoin[Quellcode]

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(Quellliste, Trennzeichen, einschließen_RegExp, optional_ersetzen)

class calibre.utils.formatter_functions.BuiltinListRe[Quellcode]

list_re(Quellliste, Trennzeichen, einschließen_RegExp, optional_ersetzen) – Erstellt eine Liste, indem zuerst Quellliste in einzelnen Elemente unter Verwendung des Trennzeichens voneinander getrennt wird. Für jedes Element in der Liste wird überprüft, ob es dem regulären Ausdruck einschließen_RegExp entspricht. Falls es dies tut, wird es zur zurückzugebenden Liste hinzugefügt. Falls optional_ersetzen keine leere Zeichenkette ist, wird das Ersetzen durchgeführt, bevor das Element zur zurückgegebenen Liste hinzugefügt wird.

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

class calibre.utils.formatter_functions.BuiltinListReGroup[Quellcode]

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

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(Liste, Richtung, Trennzeichen)

class calibre.utils.formatter_functions.BuiltinListSort[Quellcode]

list_sort(Liste, Richtung, Trennzeichen) – gibt Liste in ohne Berücksichtigung von Groß-/Kleinschreibung sortierter Form zurück. Falls Richtung null ist, wird die Liste aufsteigend sortiert, andernfalls absteigend. Die Listenelemente werden durch Trennzeichen voneinander getrennt, ebenso wie die Elemente der zurückgegebenen Liste.

list_split(list_val, sep, id_prefix)

class calibre.utils.formatter_functions.BuiltinListSplit[Quellcode]

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

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

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(Wert, Startindex, Endindex)

class calibre.utils.formatter_functions.BuiltinSubitems[Quellcode]

subitems(Wert, Startindex, Endindex) – Diese Funktion wird zum Aufteilen von Elementelisten, wie z. B. Genres verwendet. Sie interpretiert den Wert als eine kommagetrennte Liste von Elementen, wobei jedes Element eine punktgetrennte Liste darstellt. Es wird eine neue Liste zurückgegeben, die dadurch erstellt wird, dass zuerst alle punktgetrennten Elemente gesucht, für jedes so gefundene Element dessen Bestandteile von Startindex bis Endindex extrahiert, und dann die Ergebnisse wieder zusammengesetzt werden. Der erste Bestandteil einer punktgetrennten Liste besitzt die Indexnummer null. Falls ein Index negativ ist, wird vom Ende der Liste her gezählt. Einen Sonderfall stellt ein Endindex von null dar; dieser wird als die Länge der Liste interpretiert. Beispiele bei Verwenden des einfachen Vorlagemodus und unter der Annahme eines „#genre“-Werts von „A.B.C“: {#genre:subitems(0,1)} gibt „A“ zurück. {#genre:subitems(0,2)} gibt „A.B“ zurück. {#genre:subitems(1,0)} gibt „B.C“ zurück. Unter Annahme eines „#genre“-Werts von „A.B.C, D.E.F“: {#genre:subitems(0,1)} gibt „A, D“ zurück. {#genre:subitems(0,2)} gibt „A.B, D.E“ zurück.

sublist(val, start_index, end_index, separator)

class calibre.utils.formatter_functions.BuiltinSublist[Quellcode]

sublist(val, start_index, end_index, separator) – interpretiert den Wert als eine Liste von Elementen, getrennt durch ein separator (Trennzeichen). Gibt eine neue Liste, erstellt aus dem start_index zum end_index Element aus. Das erste Element hat die Zahl Null. Wenn eine Index negativ ist, dann zählt er vom Ende der Liste. Im Sonderfall, wenn end_index Null ist, wird es als Länge der Liste angenommen. Beispielsweise verwenden wir ein Basis-Template Modus und nehmen an, dass die Schlagwörter-Spalte (die durch Kommata getrennt ist) „A, B, C“: {tags:sublist(0,1,\,)} gibt „A“. {tags:sublist(-1,0,\,)} gibt „C“. {tags:sublist(0,-1,\,)} gibt „A, B“ aus.

Other

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

class calibre.utils.formatter_functions.BuiltinArguments[Quellcode]

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

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

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

class calibre.utils.formatter_functions.BuiltinEval[Quellcode]

eval(Vorlage) - wertet die Vorlage aus und gibt die lokalen Variablen (jene, die mittels der Funktion „assign“ zugewiesen wurden) anstelle der Buchmetadaten weiter. Dies erlaubt die Verwendung des Vorlagenprozessors zum Erstellen komplexer Ergebnisse aus lokalen Variablen. Da die „{“- und „}“-Zeichen Spezialfälle sind, müssen Sie „[[“ für „{“ und „]]“ für „}“ verwenden; diese werden automatisch umgewandelt. Beachten Sie, dass Präfixe und Suffixe (der Syntax |prefix|suffix) nicht innerhalb des Arguments dieser Funktion verwendet werden können, wenn der Vorlageprogrammmodus benutzt wird.

template(x)

class calibre.utils.formatter_functions.BuiltinTemplate[Quellcode]

template(x) – wertet x als eine Vorlage aus. Die Auswertung findet in ihrem eigenen Kontext statt, das heißt, dass Variablen nicht zwischen dem Aufrufer und der Vorlagenauswertung geteilt werden. Da die „{“- und „}“-Zeichen Spezialfälle sind, müssen Sie „[[“ für „{“ und „]]“ für „}“ verwenden; diese werden automatisch umgewandelt. Zum Beispiel: template(‚[[title_sort]]‘) wertet die Vorlage „{title_sort}“ aus und gibt deren Wert zurück. Beachten Sie, dass Präfixe und Suffixe (der Syntax |prefix|suffix) nicht innerhalb des Arguments dieser Funktion verwendet werden können, wenn der Vorlageprogrammmodus benutzt wird.

Relational

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

class calibre.utils.formatter_functions.BuiltinCmp[Quellcode]

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

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

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

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

class calibre.utils.formatter_functions.BuiltinCapitalize[Quellcode]

capitalize(Wert) – gibt Wert mit großen Anfangsbuchstaben zurück.

lowercase(Wert)

class calibre.utils.formatter_functions.BuiltinLowercase[Quellcode]

lowercase(Wert) – gibt Wert in Kleinbuchstaben zurück.

titlecase(Wert)

class calibre.utils.formatter_functions.BuiltinTitlecase[Quellcode]

titlecase(Wert) – gibt Wert in Überschriftenschreibweise zurück.

uppercase(Wert)

class calibre.utils.formatter_functions.BuiltinUppercase[Quellcode]

uppercase(Wert) – gibt Wert in Großbuchstaben zurück.

String manipulation

character(character_name)

class calibre.utils.formatter_functions.BuiltinCharacter[Quellcode]

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(Wert, Muster, Ersatz)

class calibre.utils.formatter_functions.BuiltinRe[Quellcode]

re(Wert, Muster, Ersatz) – gibt Wert nach Anwenden des regulären Ausdrucks zurück. Alle Fälle von Muster werden mit Ersatz ersetzt. Wie überall in Calibre sind dies zu Python kompatible reguläre Ausdrücke.

re_group(val, pattern [, template_for_group]*)

class calibre.utils.formatter_functions.BuiltinReGroup[Quellcode]

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

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

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

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

strlen(a) – Gibt die Länge der als Argument übergebenen Zeichenkette zurück.

substr(Zeichenkette, Start, Ende)

class calibre.utils.formatter_functions.BuiltinSubstr[Quellcode]

substr(Zeichenkette, Start, Ende) – gibt die Zeichen an den Positionen Start bis Ende der Zeichenkette zurück. Das erste Zeichen der Zeichenkette ist das nullte Zeichen. Falls Ende ein negativer Wert ist, werden die Zeichen entsprechend von rechts gezählt. Falls Ende null ist, steht dies für das letzte Zeichen. Zum Beispiel gibt substr(‚12345‘, 1, 0) „2345“, und substr(‚12345‘, 1, -1) „234“ zurück.

swap_around_articles(val, separator)

class calibre.utils.formatter_functions.BuiltinSwapAroundArticles[Quellcode]

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

class calibre.utils.formatter_functions.BuiltinSwapAroundComma[Quellcode]

swap_around_comma(Wert) – gibt bei einem gegebenen Wert der Form „B, A“, „A B“ zurück. Dies ist am hilfreichsten, um Namen im Format „Nachname, Vorname“ in „Vorname Nachname“ umzuwandeln. Falls kein Komma existiert, gibt die Funktion Wert unverändert zurück.

to_hex(val)

class calibre.utils.formatter_functions.BuiltinToHex[Quellcode]

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

transliterate(a)

class calibre.utils.formatter_functions.BuiltinTransliterate[Quellcode]

transliterate(a) – gibt eine Zeichenkette in einem lateinischen Alphabet zurück, gebildet durch Annähern des Klangs der Wörter in der Quellzeichenkette a. Falls beispielsweise die Quelle „Фёдор Миха́йлович Достоевский“ ist, gibt die Funktion „Fiodor Mikhailovich Dostoievskii“ zurück.

Template database functions

book_count(query, use_vl)

class calibre.utils.formatter_functions.BuiltinBookCount[Quellcode]

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

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

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

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

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

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. If ‚plain_text‘ is non-empty, return the note’s plain text. If the note doesn’t exist, return ‚‘ 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[Quellcode]

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

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

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

class calibre.utils.formatter_functions.BuiltinSetGlobals[Quellcode]

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

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

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

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

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

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

set_identifier(typ, val)[Quellcode]

If val is empty, deletes identifier of type typ

standard_field_keys()[Quellcode]

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

custom_field_keys()[Quellcode]

return a list of the custom fields in this book

all_field_keys()[Quellcode]

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

metadata_for_field(key)[Quellcode]

return metadata describing a standard or custom field.

all_non_none_fields()[Quellcode]

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

get_standard_metadata(field, make_copy)[Quellcode]

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

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

get_all_user_metadata(make_copy)[Quellcode]

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

get_user_metadata(field, make_copy)[Quellcode]

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

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

set_user_metadata(field, metadata)[Quellcode]

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

remove_stale_user_metadata(other_mi)[Quellcode]

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

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

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

Returns the tuple (display_name, formatted_value)

to_html()[Quellcode]

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