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]*)¶
ceiling(x)¶
divide(x, y)¶
floor(x)¶
fractional_part(x)¶
mod(x)¶
multiply(x [, y]*)¶
round(x)¶
subtract(x, y)¶
Boolean¶
and(value [, value]*)¶
- class calibre.utils.formatter_functions.BuiltinAnd[source]¶
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)¶
or(value [, value]*)¶
- class calibre.utils.formatter_functions.BuiltinOr[source]¶
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[source]¶
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(date1, date2)¶
- class calibre.utils.formatter_functions.BuiltinDaysBetween[source]¶
days_between(date1, date2) – return the number of days between date1 and date2. The number is positive if date1 is greater than date2, otherwise negative. If either date1 or date2 are not dates, the function returns the empty string.
today()¶
Formatting values¶
finish_formatting(val, fmt, prefix, suffix)¶
- class calibre.utils.formatter_functions.BuiltinFinishFormatting[source]¶
finish_formatting(val, fmt, prefix, suffix) – apply the format, prefix, and suffix to a value in the same way as done in a template like {series_index:05.2f| - |- }. For example, the following program produces the same output as the above template: program: finish_formatting(field(“series_index”), “05.2f”, “ - “, “ - “)
format_date(val, format_string)¶
- class calibre.utils.formatter_functions.BuiltinFormatDate[source]¶
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[source]¶
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[source]¶
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(v)¶
rating_to_stars(value, use_half_stars)¶
- class calibre.utils.formatter_functions.BuiltinRatingToStars[source]¶
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[source]¶
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()¶
approximate_formats()¶
- class calibre.utils.formatter_functions.BuiltinApproximateFormats[source]¶
approximate_formats() – return a comma-separated list of formats that at one point were associated with the book. There is no guarantee that this list is correct, although it probably is. This function can be called in template program mode using the template “{:’approximate_formats()’}”. Note that format names are always uppercase, as in EPUB. 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
booksize()¶
- class calibre.utils.formatter_functions.BuiltinBooksize[source]¶
booksize() – return value of the size field. This function works only in the GUI. If you want to use this value in save-to-disk or send-to-device templates then you must make a custom “Column built from other columns”, use the function in that column’s template, and use that column’s value in your save/send templates
connected_device_name(storage_location)¶
- class calibre.utils.formatter_functions.BuiltinConnectedDeviceName[source]¶
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[source]¶
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()¶
current_library_path()¶
current_virtual_library_name()¶
field(lookup_name)¶
formats_modtimes(date_format)¶
- class calibre.utils.formatter_functions.BuiltinFormatsModtimes[source]¶
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[source]¶
formats_paths() – return a comma-separated list of colon-separated items representing full path to the formats of a book. You can use the select function to get the path for a specific format. Note that format names are always uppercase, as in EPUB.
formats_sizes()¶
- class calibre.utils.formatter_functions.BuiltinFormatsSizes[source]¶
formats_sizes() – return a comma-separated list of colon-separated items representing sizes in bytes of the formats of a book. You can use the select function to get the size for a specific format. Note that format names are always uppercase, as in EPUB.
has_cover()¶
is_marked()¶
language_codes(lang_strings)¶
language_strings(lang_codes, localize)¶
- class calibre.utils.formatter_functions.BuiltinLanguageStrings[source]¶
language_strings(lang_codes, localize) – return the strings for the language codes passed in lang_codes. If localize is zero, return the strings in English. If localize is not zero, return the strings in the language of the current locale. Lang_codes is a comma-separated list.
ondevice()¶
- class calibre.utils.formatter_functions.BuiltinOndevice[source]¶
ondevice() – return Yes if ondevice is set, otherwise return the empty string. This function works only in the GUI. If you want to use this value in save-to-disk or send-to-device templates then you must make a custom “Column built from other columns”, use the function in that column’s template, and use that column’s value in your save/send templates
raw_field(lookup_name [, optional_default])¶
raw_list(lookup_name, separator)¶
series_sort()¶
user_categories()¶
- class calibre.utils.formatter_functions.BuiltinUserCategories[source]¶
user_categories() – return a comma-separated list of the user categories that contain this book. This function works only in the GUI. If you want to use these values in save-to-disk or send-to-device templates then you must make a custom “Column built from other columns”, use the function in that column’s template, and use that column’s value in your save/send templates
virtual_libraries()¶
- class calibre.utils.formatter_functions.BuiltinVirtualLibraries[source]¶
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[source]¶
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)¶
field_exists(field_name)¶
ifempty(val, text if empty)¶
test(val, text if not empty, text if empty)¶
Iterating over values¶
first_non_empty(value [, value]*)¶
lookup(val, [pattern, field,]+ else_field)¶
- class calibre.utils.formatter_functions.BuiltinLookup[source]¶
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[source]¶
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[source]¶
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[source]¶
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[source]¶
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(val, index, separator)¶
- class calibre.utils.formatter_functions.BuiltinListitem[source]¶
list_item(val, index, separator) – interpret the value as a list of items separated by separator, returning the index`th item. The first item is number zero. The last item can be returned using `list_item(-1,separator). If the item is not in the list, then the empty value is returned. The separator has the same meaning as in the count function.
select(val, key)¶
str_in_list(val, separator, [string, found_val, ]+ not_found_val)¶
- class calibre.utils.formatter_functions.BuiltinStrInList[source]¶
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[source]¶
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[source]¶
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[source]¶
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[source]¶
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(list1, list2, separator)¶
- class calibre.utils.formatter_functions.BuiltinListIntersection[source]¶
list_intersection(list1, list2, separator) – return a list made by removing from list1 any item not found in list2, using a case-insensitive comparison. The items in list1 and list2 are separated by separator, as are the items in the returned list.
list_join(with_separator, list1, separator1 [, list2, separator2]*)¶
- class calibre.utils.formatter_functions.BuiltinListJoin[source]¶
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(src_list, separator, include_re, opt_replace)¶
- class calibre.utils.formatter_functions.BuiltinListRe[source]¶
list_re(src_list, separator, include_re, opt_replace) – Construct a list by first separating src_list into items using the separator character. For each item in the list, check if it matches include_re. If it does, then add it to the list to be returned. If opt_replace is not the empty string, then apply the replacement before adding the item to the returned list.
list_re_group(src_list, separator, include_re, search_re [, group_template]+)¶
- class calibre.utils.formatter_functions.BuiltinListReGroup[source]¶
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[source]¶
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(list, direction, separator)¶
- class calibre.utils.formatter_functions.BuiltinListSort[source]¶
list_sort(list, direction, separator) – return list sorted using a case-insensitive sort. If direction is zero, the list is sorted ascending, otherwise descending. The list items are separated by separator, as are the items in the returned list.
list_split(list_val, sep, id_prefix)¶
- class calibre.utils.formatter_functions.BuiltinListSplit[source]¶
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[source]¶
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[source]¶
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[source]¶
subitems(val, start_index, end_index) – This function is used to break apart lists of items such as genres. It interprets the value as a comma-separated list of items, where each item is a period-separated list. Returns a new list made by first finding all the period-separated items, then for each such item extracting the start_index to the end_index components, then combining the results back together. The first component in a period-separated list has an index of zero. If an index is negative, then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list. Example using basic template mode and assuming a #genre value of “A.B.C”: {#genre:subitems(0,1)} returns “A”. {#genre:subitems(0,2)} returns “A.B”. {#genre:subitems(1,0)} returns “B.C”. Assuming a #genre value of “A.B.C, D.E.F”, {#genre:subitems(0,1)} returns “A, D”. {#genre:subitems(0,2)} returns “A.B, D.E”
sublist(val, start_index, end_index, separator)¶
- class calibre.utils.formatter_functions.BuiltinSublist[source]¶
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[source]¶
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)¶
globals(id[=expression] [, id[=expression]]*)¶
- class calibre.utils.formatter_functions.BuiltinGlobals[source]¶
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.
print(a[, b]*)¶
Recursion¶
eval(template)¶
- class calibre.utils.formatter_functions.BuiltinEval[source]¶
eval(template) – evaluates the template, passing the local variables (those ‘assign’ed to) instead of the book metadata. This permits using the template processor to construct complex results from local variables. Because the { and } characters are special, you must use [[ for the { character and ]] for the } character; they are converted automatically. Note also that prefixes and suffixes (the |prefix|suffix syntax) cannot be used in the argument to this function when using template program mode.
template(x)¶
- class calibre.utils.formatter_functions.BuiltinTemplate[source]¶
template(x) – evaluates x as a template. The evaluation is done in its own context, meaning that variables are not shared between the caller and the template evaluation. Because the { and } characters are special, you must use [[ for the { character and ]] for the } character; they are converted automatically. For example, template(‘[[title_sort]]’) will evaluate the template {title_sort} and return its value. Note also that prefixes and suffixes (the |prefix|suffix syntax) cannot be used in the argument to this function when using template program mode.
Relational¶
cmp(x, y, lt, eq, gt)¶
first_matching_cmp(val, [cmp1, result1,]+, else_result)¶
- class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp[source]¶
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[source]¶
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[source]¶
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)¶
lowercase(val)¶
titlecase(val)¶
uppercase(val)¶
String manipulation¶
character(character_name)¶
re(val, pattern, replacement)¶
re_group(val, pattern [, template_for_group]*)¶
- class calibre.utils.formatter_functions.BuiltinReGroup[source]¶
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[source]¶
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]*)¶
strcat_max(max, string1 [, prefix2, string2]*)¶
- class calibre.utils.formatter_functions.BuiltinStrcatMax[source]¶
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)¶
substr(str, start, end)¶
- class calibre.utils.formatter_functions.BuiltinSubstr[source]¶
substr(str, start, end) – returns the start’th through the end’th characters of str. The first character in str is the zero’th character. If end is negative, then it indicates that many characters counting from the right. If end is zero, then it indicates the last character. For example, substr(‘12345’, 1, 0) returns ‘2345’, and substr(‘12345’, 1, -1) returns ‘234’.
swap_around_articles(val, separator)¶
- class calibre.utils.formatter_functions.BuiltinSwapAroundArticles[source]¶
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(val)¶
to_hex(val)¶
transliterate(a)¶
- class calibre.utils.formatter_functions.BuiltinTransliterate[source]¶
transliterate(a) – Returns a string in a latin alphabet formed by approximating the sound of the words in the source string. For example, if the source is “Фёдор Миха́йлович Достоевский” the function returns “Fiodor Mikhailovich Dostoievskii”.
Template database functions¶
book_count(query, use_vl)¶
book_values(column, query, sep, use_vl)¶
- class calibre.utils.formatter_functions.BuiltinBookValues[source]¶
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[source]¶
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[source]¶
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)¶
get_link(field_name, field_value)¶
get_note(field_name, field_value, plain_text)¶
- class calibre.utils.formatter_functions.BuiltinGetNote[source]¶
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[source]¶
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[source]¶
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[source]¶
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]]*)¶
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=('Unknown',), other=None, template_cache=None, formatter=None)[source]¶
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)[source]¶
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>>)[source]¶
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()[source]¶
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)[source]¶
Set all identifiers. Note that if you previously set ISBN, calling this method will delete it.
- standard_field_keys()[source]¶
return a list of all possible keys, even if this book doesn’t have them
- all_non_none_fields()[source]¶
Return a dictionary containing all non-None metadata fields, including the custom ones.
- get_standard_metadata(field, make_copy)[source]¶
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)[source]¶
return a dict containing all the standard field metadata associated with the book.
- get_all_user_metadata(make_copy)[source]¶
return a dict containing all the custom field metadata associated with the book.
- get_user_metadata(field, make_copy)[source]¶
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)[source]¶
store custom field metadata into the object. Field is the key name not the label
- set_user_metadata(field, metadata)[source]¶
store custom field metadata for one column into the object. Field is the key name not the label
- remove_stale_user_metadata(other_mi)[source]¶
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)[source]¶
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)[source]¶
Merge the information in other into self. In case of conflicts, the information in other takes precedence, unless the information in other is NULL.
- 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