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.
Aritmetik¶
add¶
add(x [, y]*) – returnerar summan av dess argument. Utlöser ett undantag om ett argument inte är ett tal. I de flesta fall kan du använda operatorn + istället för den här funktionen.
ceiling¶
ceiling(value) – returns the smallest integer greater than or equal to value. Throws an exception if value is not a number.
divide¶
divide(x, y) – returns x / y. Throws an exception if either x or y are not numbers. This function can usually be replaced by the / operator.
floor¶
floor(value) – returnerar det största heltalet mindre än eller lika med value. Utlöser ett undantag om value inte är ett tal.
fractional_part¶
fractional_part(value) – returnerar den del av värdet som kommer efter decimaltecknet. Till exempel returnerar fractional_part(3.14) 0.14. Utlöser ett undantag om value inte är ett tal.
mod¶
mod(value, y) – returns the floor of the remainder of value / y. Throws an exception if either value or y is not a number.
multiply¶
multiply(x [, y]*) – returns the product of its arguments. Throws an exception if any argument is not a number. This function can usually be replaced by the * operator.
round¶
round(value) – returns the nearest integer to value. Throws an exception if value is not a number.
subtract¶
subtract(x, y) – returnerar x - y. Utlöser ett undantag om antingen x eller y inte är tal. Denna funktion kan vanligtvis ersättas av operatorn -.
Booleskt¶
and¶
and(value [, value]*) – returnerar strängen '1' om alla värden inte är tomma, annars returnerar den den tomma strängen. Du kan ha så många värden du vill. I de flesta fall kan du använda operatorn && istället för den här funktionen. En anledning att inte ersätta and() med && är när kortslutning kan ändra resultaten på grund av biverkningar. Till exempel kommer och(a='',b=5) alltid att utföra båda tilldelningarna, medan operatorn && inte gör den andra.
not¶
not(value) – returns the string '1' if the value is empty, otherwise returns the empty string. This function can usually be replaced with the unary not (!) operator.
or¶
or(value [, value]*) – returns the string '1' if any value is not empty, otherwise returns the empty string. You can have as many values as you want. This function can usually be replaced by the || operator. A reason it cannot be replaced is if short-circuiting will change the results because of side effects.
Databasfunktioner¶
annotation_count¶
annotation_count() – returnerar det totala antalet noteringar av alla typer som är kopplade till den aktuella boken. Den här funktionen fungerar bara i det grafiska gränssnittet och innehållsservern.
approximate_formats¶
approximate_formats() – returnerar en kommaseparerad lista över format som är associerade med boken. Eftersom listan kommer från calibres databas istället för filsystemet finns det ingen garanti för att listan är korrekt, även om den förmodligen är det. Observera att resulterande formatnamn alltid är versaler, som i EPUB. Funktionen approximate_formats() är mycket snabbare än funktionerna formats_....
Denna funktion fungerar bara i det grafiska gränssnittet. Om du vill använda dessa värden i mallar för att spara till disk eller skicka till enhet måste du skapa en anpassad ”Kolumn byggd från andra kolumner”, använda funktionen i den kolumnens mall och använda den kolumnens värde i dina spara-/skicka-mallar.
book_count¶
book_count(query, use_vl) – returnerar antalet böcker som hittats genom att söka efter query. Om use_vl är 0 (noll) ignoreras virtuella bibliotek. Denna funktion och dess tillhörande book_values() är särskilt användbara vid mallsökningar och stöder sökningar som kombinerar information från många böcker, till exempel att söka efter serier med endast en bok. Den kan inte användas i sammansatta kolumner om inte justeringen allow_template_database_functions_in_composites är inställd på True. Den kan bara användas i det grafiska gränssnittet.
Till exempel använder denna mallsökning denna funktion och dess tillhörande för att hitta alla serier med endast en bok:
Definiera en lagrad mall (med Inställningar → Avancerat → Mallfunktioner) med namnet
series_only_one_book(namnet är godtyckligt). Mallen är:program: vals = globals(vals=''); if !vals then all_series = book_values('series', 'series:true', ',', 0); for series in all_series: if book_count('series:="' & series & '"', 0) == 1 then vals = list_join(',', vals, ',', series, ',') fi rof; set_globals(vals) fi; str_in_list(vals, ',', $series, 1, '')Första gången mallen körs (den första boken som kontrolleras) lagrar den resultaten av databassökningarna i en ”global” mallvariabel med namnet ”vals”. Dessa resultat används för att kontrollera efterföljande böcker utan att göra om sökningarna.
Använd den lagrade mallen i en mallsökning:
template:"program: series_only_one_book()#@#:n:1"Att använda en lagrad mall istället för att lägga in mallen i sökningen eliminerar problem som orsakas av kravet på att använda escape-citationstecken i sökuttryck.
Denna funktion kan endast användas i det grafiska användargränssnittet och innehållsservern.
book_values¶
book_values(column, query, sep, use_vl) – returnerar en lista över de unika värdena som finns i kolumnen column (ett söknamn), separerade med sep, i de böcker som hittas genom att söka efter query. Om use_vl är 0 (noll) ignoreras virtuella bibliotek. Denna funktion och dess tillhörande book_count() är särskilt användbara vid mallsökningar och stöder sökningar som kombinerar information från många böcker, till exempel att söka efter serier med endast en bok. Den kan inte användas i sammansatta kolumner om inte justeringen allow_template_database_functions_in_composites är inställd på True. Denna funktion kan bara användas i det grafiska gränssnittet och innehållsservern.
extra_file_modtime¶
extra_file_modtime(file_name, format_string) – returns the modification time of the extra file file_name in the book’s data/ folder if it exists, otherwise -1. The modtime is formatted according to format_string (see format_date() for details). If format_string is the empty string, returns the modtime as the floating point number of seconds since the epoch. See also the functions has_extra_files(), extra_file_names() and extra_file_size(). The epoch is OS dependent. This function can be used only in the GUI and the content server.
extra_file_names¶
extra_file_names(sep [, pattern]) – returns a sep-separated list of extra files in the book’s data/ folder. If the optional parameter pattern, a regular expression, is supplied then the list is filtered to files that match pattern. The pattern match is case insensitive. See also the functions has_extra_files(), extra_file_modtime() and extra_file_size(). This function can be used only in the GUI and the content server.
extra_file_size¶
extra_file_size(file_name) – returns the size in bytes of the extra file file_name in the book’s data/ folder if it exists, otherwise -1. See also the functions has_extra_files(), extra_file_names() and extra_file_modtime(). This function can be used only in the GUI and the content server.
formats_modtimes¶
formats_modtimes(date_format_string) – returnerar en kommaseparerad lista med kolonseparerade objekt FMT:DATE som representerar ändringstider för formaten i en bok. Parametern date_format_string anger hur datumet ska formateras. Se funktionen format_date() för mer information. Du kan använda funktionen select() för att hämta ändringstiden för ett specifikt format. Observera att formatnamn alltid är versaler, som i EPUB.
formats_path_segments¶
formats_path_segments(with_author, with_title, with_format, with_ext, sep) – return parts of the path to a book format in the calibre library separated by sep. The parameter sep should usually be a slash ('/'). One use is to be sure that paths generated in Save to disk and Send to device templates are shortened consistently. Another is to be sure the paths on the device match the paths in the calibre library.
A book path consists of 3 segments: the author, the title including the calibre database id in parentheses, and the format (author - title). Calibre can shorten any of the three because of file name length limitations. You choose which segments to include by passing 1 for that segment. If you don’t want a segment then pass 0 or the empty string for that segment. For example, the following returns just the format name without the extension:
formats_path_segments(0, 0, 1, 0, '/')
Because there is only one segment the separator is ignored.
If there are multiple formats (multiple extensions) then one of the extensions will be picked at random. If you care about which extension is used then get the path without the extension then add the desired extension to it.
Examples: Assume there is a book in the calibre library with an epub format by Joe Blogs with title ’Help’. It would have the path
Joe Blogs/Help - (calibre_id)/Help - Joe Blogs.epub
The following shows what is returned for various parameters:
formats_path_segments(0, 0, 1, 0, '/')returns Help - Joe Blogsformats_path_segments(0, 0, 1, 1, '/')returns Help - Joe Blogs.epubformats_path_segments(1, 0, 1, 1, '/')returns Joe Blogs/Help - Joe Blogs.epubformats_path_segments(1, 0, 1, 0, '/')returns Joe Blogs/Help - Joe Blogsformats_path_segments(0, 1, 0, 0, '/')returns Help - (calibre_id)
formats_paths¶
formats_paths([separator]) – returnerar en separator-separerad lista över kolonseparerade objekt FMT:PATH som anger den fullständiga sökvägen till formaten för en bok. Argumentet separator är valfritt. Om det inte anges är separatorn ', ' (kommamellanslag). Om separatorn är ett komma kan du använda funktionen select() för att hämta sökvägen för ett specifikt format. Observera att formatnamn alltid är versaler, som i EPUB.
formats_sizes¶
formats_sizes() – returnerar en kommaseparerad lista med kolonseparerade FMT:SIZE-element som anger storleken på formaten för en bok i byte. Du kan använda funktionen select() för att hämta storleken för ett specifikt format. Observera att formatnamn alltid är versaler, som i EPUB.
get_link¶
get_link(field_name, field_value) – fetch the link for field field_name with value field_value. If there is no attached link, return the empty string. Examples:
The following returns the link attached to the tag
Fiction:get_link('tags', 'Fiction')
This template makes a list of the links for all the tags associated with a book in the form
value:link, ...:program: ans = ''; for t in $tags: l = get_link('tags', t); if l then ans = list_join(', ', ans, ',', t & ':' & get_link('tags', t), ',') fi rof; ans
This function works only in the GUI and the content server.
get_note¶
get_note(field_name, field_value, plain_text) – hämta anteckningen för fältet field_name med värdet field_value. Om plain_text är tom, returnera anteckningens HTML inklusive bilder. Om plain_text är 1 (eller '1'), returnera anteckningens klartext. Om anteckningen inte finns, returnera den tomma strängen i båda fallen. Exempel:
Returnera HTML-koden för anteckningen som är kopplad till taggen Fiction:
program: get_note('taggar', 'Fiction', '')
Returnera den klara texten för anteckningen som är kopplad till författaren Isaac Asimov:
program: get_note('authors', 'Isaac Asimov', 1)
Denna funktion fungerar endast i det grafiska gränssnittet och innehållsservern.
has_extra_files¶
has_extra_files([pattern]) – returnerar antalet extra filer, annars ’’ (den tomma strängen). Om den valfria parametern pattern (ett reguljärt uttryck) anges filtreras listan till filer som matchar pattern innan filerna räknas. Mönstermatchningen är inte skiftlägeskänslig. Se även funktionerna extra_file_names(), extra_file_size() och extra_file_modtime(). Denna funktion kan endast användas i det grafiska gränssnittet och innehållsservern.
has_note¶
has_note(field_name, field_value). Kontrollera om ett fält har en anteckning. Denna funktion har två varianter:
om
field_valueinte är''(den tomma strängen) returnera'1'om värdetfield_valuei fältetfield_namehar en anteckning, annars''.Exempel:
has_note('tags', 'Fiction')returnerar'1'om taggenfictionhar en bifogad anteckning, annars''.Om
field_valueär''returnerar du en lista med värden ifield_namesom har en anteckning. Om inget objekt i fältet har en anteckning returnerar du''. Denna variant är användbar för att visa kolumnikoner om något värde i fältet har en anteckning, snarare än ett specifikt värde.Exempel:
has_note('authors', '')returnerar en lista över författare som har anteckningar, eller''om ingen författare har en anteckning.
Du kan testa om alla värden i field_name har en anteckning genom att jämföra listlängden för den här funktionens returvärde med listlängden för värdena i field_name. Exempel:
list_count(has_note('authors', ''), '&') ==# list_count_field('authors')
Denna funktion fungerar bara i det grafiska gränssnittet och innehållsservern.
Datumfunktioner¶
date_arithmetic¶
date_arithmetic(value, calc_spec, fmt) – Calculate a new date from value using calc_spec. Return the new date formatted according to optional fmt: if not supplied then the result will be in ISO format. The calc_spec is a string formed by concatenating pairs of vW (valueWhat) where v is a possibly-negative number and W is one of the following letters:
s: addvseconds todatem: addvminutes todateh: addvhours todated: addvdays todatew: addvweeks todatey: addvyears todate, where a year is 365 days.
Example: '1s3d-1m' will add 1 second, add 3 days, and subtract 1 minute from date.
days_between¶
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¶
today() – returnerar en datum+tid-sträng för idag (nu). Detta värde är utformat för användning i format_datum eller days_between, men kan manipuleras som vilken annan sträng som helst. Datumet är i ISO datum/tid-format.
Formaterar värden¶
f_string¶
f_string(string) – tolka string på samma sätt som Python tolkar f-strängar. Den avsedda användningen är att förenkla långa sekvenser av str & str eller strcat(a,b,c)-uttryck.
Text mellan klammerparenteser ({ och }) måste vara malluttryck i allmänt programläge. Uttrycken, som kan vara uttryckslistor, utvärderas i det aktuella sammanhanget (aktuell bok och lokala variabler). Text som inte är mellan klammerparenteser skickas igenom oförändrad.
Exempel:
f_string('Här är titeln: {$title}')- returnerar strängen med{$title}ersatt med titeln på den aktuella boken. Om till exempel bokens titel är 20 000 ligor under havet returnerarf_string()Här är titeln: 20 000 ligor under havet.Om det aktuella datumet är den 18 september 2025, returnerar denna
f_string()f_string("Dagens datum: {d = today(); format_date(d, 'd')} av {format_date(d, 'MMMM')}, {format_date(d, 'yyyy')}")
strängen Dagens datum: den 18 september 2025. Observera uttryckslistan (en tilldelning sedan ett
if-uttryck) som används i den första{ ... }-gruppen för att tilldela dagens datum till en lokal variabel.Om boken är bok #3 i en serie med namnet Foo som har 5 böcker, då returnerar denna mall
program: if $series then series_count = book_count('series:"""=' & $series & '"""', 0); returnera f_string("{$series}, bok {$series_index} av {series_count}") fi; return 'Denna bok ingår inte i en serie'returnerar Foo, bok 3 av 5
finish_formatting¶
finish_formatting(value, format, prefix, suffix) – apply the format, prefix, and suffix to the value in the same way as done in a template like {series_index:05.2f| - |- }. This function is provided to ease conversion of complex single-function- or template-program-mode templates to GPM Templates. For example, the following program produces the same output as the above template:
program: finish_formatting(field("series_index"), "05.2f", " - ", " - ")
Another example: for the template:
{series:re(([^\s])[^\s]+(\s|$),\1)}{series_index:0>2s| - | - }{title}
use:
program:
strcat(
re(field('series'), '([^\s])[^\s]+(\s|$)', '\1'),
finish_formatting(field('series_index'), '0>2s', ' - ', ' - '),
field('title')
)
format_date¶
format_date(value, format_string) – formatera value, som måste vara en datumsträng, med format_string, vilket returnerar en sträng. Det är bäst om datumet är i ISO-format eftersom användning av andra datumformat ofta orsakar fel eftersom det faktiska datumvärdet inte kan bestämmas entydigt. Observera att funktionen format_date_field() är både snabbare och mer tillförlitlig.
Formateringskoderna är: [LISTA]
format_date_field¶
format_date_field(field_name, format_string) – formaterar värdet i fältet field_name, vilket måste vara söknamnet för ett datumfält, antingen standard eller anpassat. Se format_date() för formateringskoder. Den här funktionen är mycket snabbare än format_date() och bör användas när du formaterar värdet i ett fält (kolumn). Den är också mer tillförlitlig eftersom den fungerar direkt på det underliggande datumet. Den kan inte användas för beräknade datum eller datum i strängvariabler. Exempel:
format_date_field('pubdate', 'åååå.MM.dd')
format_date_field('#date_read', 'MMM dd, åååå')
format_duration¶
format_duration(värde, mall, [största_enhet]) – formaterar värdet, ett antal sekunder, till en sträng som visar veckor, dagar, timmar, minuter och sekunder. Om värdet är ett flyttal avrundas det till närmaste heltal. Du väljer hur du formaterar värdet med hjälp av en mall som består av värdeväljare omgivna av [ och ] tecken. Väljarna är:
[w]: veckor[d]: dagar[h]: timmar[m]: minuter[s]: sekunder
Du kan lägga in godtycklig text mellan väljare.
Följande exempel använder en varaktighet på 2 dagar (172 800 sekunder), 1 timme (3 600 sekunder) och 20 sekunder, vilket totalt blir 176 420 sekunder.
[LISTA]
format_number¶
format_number(value, template) – interprets the value as a number and formats that number using a Python formatting template such as {0:5.2f} or {0:,d} or ${0:5,.2f}. The formatting template must begin with {0: and end with } as in the above examples. Exception: you can leave off the leading ”{0:” and trailing ”}” if the format template contains only a format. See the Template Language and the Python documentation for more examples. Returns the empty string if formatting fails.
human_readable¶
human_readable(value) – förväntar sig att value är ett tal och returnerar en sträng som representerar det talet i KB, MB, GB, etc.
rating_to_stars¶
rating_to_stars(value, use_half_stars) – Returns the value as string of star (★) characters. The value must be a number between 0 and 5. Set use_half_stars to 1 if you want half star characters for fractional numbers available with custom ratings columns.
Grafiska användargränssnittsfunktioner¶
selected_books¶
selected_books([sorted_by, ascending]) – returns a list of book ids in selection order for the currently selected books.
This function can be used only in the GUI.
selected_column¶
selected_column() – returns the lookup name of the column containing the currently selected cell. It returns '' if no cell is selected.
This function can be used only in the GUI.
show_dialog¶
show_dialog(html_or_text) – show a dialog containing the html or text. The function returns '1' if the user presses OK, '' if Cancel.
This function can be used only in the GUI.
sort_book_ids¶
sort_book_ids(book_ids, sorted_by, ascending [, sorted_by, ascending]*) – returns the list of book ids sorted by the column specified by the lookup name in sorted_by in the order specified by ascending. If ascending is '1' then the books are sorted by the value in the ’sorted_by’ column in ascending order, otherwise in descending order. You can have multiple pairs of sorted_by, ascending. The first pair specifies the major order.
This function can be used only in the GUI.
Hämta värden från metadata¶
booksize¶
booksize() – returnerar värdet för calibre size-fältet. Returnerar ’’ om boken inte har några format.
Denna funktion fungerar bara i det grafiska gränssnittet. Om du vill använda detta värde i mallar för att spara till disk eller skicka till enhet måste du skapa en anpassad ”Kolumn byggd från andra kolumner”, använda funktionen i den kolumnens mall och använda den kolumnens värde i dina spara-/skicka-mallar.
connected_device_name¶
connected_device_name(storage_location_key) – if a device is connected then return the device name, otherwise return the empty string. Each storage location on a device has its own device name. The storage_location_key names are 'main', 'carda' and 'cardb'. This function works only in the GUI.
connected_device_uuid¶
connected_device_uuid(storage_location_key) – if a device is connected then return the device uuid (unique id), otherwise return the empty string. Each storage location on a device has a different uuid. The storage_location_key location names are 'main', 'carda' and 'cardb'. This function works only in the GUI.
current_library_name¶
current_library_name() – returnerar det sista namnet på sökvägen till det aktuella calibre-biblioteket.
current_library_path¶
current_library_path() – returnerar den fullständiga sökvägen till det aktuella calibre-biblioteket.
current_virtual_library_name¶
current_virtual_library_name() – return the name of the current virtual library if there is one, otherwise the empty string. Library name case is preserved. Example:
program: current_virtual_library_name()
This function works only in the GUI.
field¶
field(lookup_name) – returns the value of the metadata field with lookup name lookup_name. The $ prefix can be used instead of the function, as in $tags.
has_cover¶
has_cover() – returnerar 'Yes' om boken har ett omslag, annars den tomma strängen.
is_marked¶
is_marked() – check whether the book is marked in calibre. If it is then return the value of the mark, either 'true' (lower case) or a comma-separated list of named marks. Returns '' (the empty string) if the book is not marked. This function works only in the GUI.
language_codes¶
language_codes(lang_strings) – returnerar språkkoderna för språknamnen som skickas i lang_strings. Strängarna måste vara på språket för den aktuella språkinställningen. lang_strings är en kommaseparerad lista.
language_strings¶
language_strings(value, localize) – returnerar språknamnen för språkkoderna (se här för namn och koder) som skickats i value. Exempel: {languages:language_strings()}. Om localize är noll, returnerar strängarna på engelska. Om localize inte är noll, returnerar strängarna på språket för den aktuella lokalen. lang_codes är en kommaseparerad lista.
ondevice¶
ondevice() – return the string 'Yes' if ondevice is set, otherwise return the empty string. This function works only in the GUI. If you want to use this value in save-to-disk or send-to-device templates then you must make a custom ”Column built from other columns”, use the function in that column’s template, and use that column’s value in your save/send templates.
raw_field¶
raw_field(lookup_name [, optional_default]) – returns the metadata field named by lookup_name without applying any formatting. It evaluates and returns the optional second argument optional_default if the field’s value is undefined (None). The $$ prefix can be used instead of the function, as in $$pubdate.
raw_list¶
raw_list(lookup_name, separator) – returns the metadata list named by lookup_name without applying any formatting or sorting, with the items separated by separator.
series_sort¶
series_sort() – returnerar seriens sorterade värden.
user_categories¶
user_categories() – returnerar en kommaseparerad lista över användarkategorierna som innehåller den här boken. Den här funktionen fungerar bara i det grafiska gränssnittet. Om du vill använda dessa värden i mallar för att spara till disk eller skicka till enhet måste du skapa en anpassad ”Kolumn byggd från andra kolumner”, använda funktionen i den kolumnens mall och använda den kolumnens värde i dina spara-/skicka-mallar.
virtual_libraries¶
virtual_libraries() – returnerar en kommaseparerad lista över virtuella bibliotek som innehåller den här boken. Den här funktionen fungerar bara i det grafiska gränssnittet. Om du vill använda dessa värden i mallar för att spara till disk eller skicka till enhet måste du skapa en anpassad Kolumn byggd från andra kolumner, använda funktionen i den kolumnens mall och använda den kolumnens värde i dina spara-/skicka-mallar.
Iterera över värden¶
first_non_empty¶
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¶
lookup(value, [ pattern, key, ]* else_key) – The patterns will be checked against the value in order. If a pattern matches then the value of the field named by key is returned. If no pattern matches then the value of the field named by else_key is returned. See also the switch() function.
switch¶
switch(value, [patternN, valueN,]+ else_value) – for each patternN, valueN pair, checks if the value matches the regular expression patternN and if so returns the associated valueN. If no patternN matches, then else_value is returned. You can have as many patternN, valueN pairs as you wish. The first match is returned.
switch_if¶
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.
Listmanipulation¶
list_count¶
list_count(value, separator) – interprets the value as a list of items separated by separator and returns the number of items in the list. Most lists use a comma as the separator, but authors uses an ampersand (&).
Examples: {tags:list_count(,)}, {authors:list_count(&)}.
Aliases: count(), list_count()
list_count_field¶
list_count_field(lookup_name)– returns the count of items in the field with the lookup name lookup_name. The field must be multi-valued such as authors or tags, otherwise the function raises an error. This function is much faster than list_count() because it operates directly on calibre data without converting it to a string first. Example: list_count_field('tags').
list_count_matching¶
list_count_matching(value, pattern, separator) – interprets value as a list of items separated by separator, returning the number of items in the list that match the regular expression pattern.
Aliases: list_count_matching(), count_matching()
list_difference¶
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¶
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¶
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¶
list_join(with_separator, list1, separator1 [, list2, separator2]*) – return a list made by joining the items in the source lists (list1 etc) using with_separator between the items in the result list. Items in each source list[123...] are separated by the associated separator[123...]. A list can contain zero values. It can be a field like publisher that is single-valued, effectively a one-item list. Duplicates are removed using a case-insensitive comparison. Items are returned in the order they appear in the source lists. If items on lists differ only in letter case then the last is used. All separators can be more than one character.
Example:
program:
list_join('#@#', $authors, '&', $tags, ',')
You can use list_join on the results of previous calls to list_join as follows:
program:
a = list_join('#@#', $authors, '&', $tags, ',');
b = list_join('#@#', a, '#@#', $#genre, ',', $#people, '&', 'some value', ',')
You can use expressions to generate a list. For example, assume you want items for authors and #genre, but with the genre changed to the word ”Genre: ” followed by the first letter of the genre, i.e. the genre ”Fiction” becomes ”Genre: F”. The following will do that:
program:
list_join('#@#', $authors, '&', list_re($#genre, ',', '^(.).*$', 'Genre: \1'), ',')
list_re¶
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¶
list_re_group(src_list, separator, include_re, search_re [,template_for_group]*) – Like list_re() except replacements are not optional. It uses re_group(item, search_re, template ...) when doing the replacements.
list_remove_duplicates¶
list_remove_duplicates(list, separator) – return a list made by removing duplicate items in list. If items differ only in case then the last is returned. The items in list are separated by separator, as are the items in the returned list.
list_sort¶
list_sort(value, direction, separator) – return value sorted using a case-insensitive lexical sort. If direction is zero (number or character), value is sorted ascending, otherwise descending. The list items are separated by separator, as are the items in the returned list.
list_split¶
list_split(list_val, sep, id_prefix) – splits list_val into separate values using sep, then assigns the values to local variables named id_prefix_N where N is the position of the value in the list. The first item has position 0 (zero). The function returns the last element in the list.
Example:
list_split('one:two:foo', ':', 'var')
is equivalent to:
var_0 = 'one'
var_1 = 'two'
var_2 = 'foo'
list_union¶
list_union(list1, list2, separator) – return a list made by merging the items in list1 and list2, removing duplicate items using a case-insensitive comparison. If items differ in case, the one in list1 is used. The items in list1 and list2 are separated by separator, as are the items in the returned list.
Aliases: merge_lists(), list_union()
range¶
range(start, stop, step, limit) – returns a list of numbers generated by looping over the range specified by the parameters start, stop, and step, with a maximum length of limit. The first value produced is ’start’. Subsequent values next_v = current_v + step. The loop continues while next_v < stop assuming step is positive, otherwise while next_v > stop. An empty list is produced if start fails the test: start >= stop if step is positive. The limit sets the maximum length of the list and has a default of 1000. The parameters start, step, and limit are optional. Calling range() with one argument specifies stop. Two arguments specify start and stop. Three arguments specify start, stop, and step. Four arguments specify start, stop, step and limit.
Examples:
range(5) -> '0, 1, 2, 3, 4'
range(0, 5) -> '0, 1, 2, 3, 4'
range(-1, 5) -> '-1, 0, 1, 2, 3, 4'
range(1, 5) -> '1, 2, 3, 4'
range(1, 5, 2) -> '1, 3'
range(1, 5, 2, 5) -> '1, 3'
range(1, 5, 2, 1) -> error(limit exceeded)
subitems¶
subitems(value, start_index, end_index) – This function breaks apart lists of tag-like hierarchical items such as genres. It interprets the value as a comma- separated list of tag-like items, where each item is a period-separated list. It returns a new list made by extracting from each item the components from start_index to end_index, then merging the results back together. Duplicates are removed. The first subitem in a period-separated list has an index of zero. If an index is negative then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list.
Examples:
Assuming a #genre column containing ”A.B.C”:
{#genre:subitems(0,1)}returns ”A”{#genre:subitems(0,2)}returns ”A.B”{#genre:subitems(1,0)}returns ”B.C”
Assuming a #genre column containing ”A.B.C, D.E”:
{#genre:subitems(0,1)}returns ”A, D”{#genre:subitems(0,2)}returns ”A.B, D.E”
sublist¶
sublist(value, start_index, end_index, separator) – interpret the value as a list of items separated by separator, returning a new list made from the items from start_index to end_index. The first item is number zero. If an index is negative, then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list.
Examples assuming that the tags column (which is comma-separated) contains ”A, B, C”:
{tags:sublist(0,1,\,)}returns ”A”{tags:sublist(-1,0,\,)}returns ”C”{tags:sublist(0,-1,\,)}returns ”A, B”
Listuppslag¶
identifier_in_list¶
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 ('').
Visar dokumentationen på engelska på grund av FFML-felet: Missing closing ”``” for CODE_TEXT on line 1 in ”identifier_in_list”
list_contains¶
list_contains(value, separator, [ pattern, found_val, ]* not_found_val) – tolka value som en lista med objekt separerade med separator, och kontrollera pattern mot varje objekt i listan. Om pattern matchar ett objekt returneras found_val, annars returneras not_found_val. Paret pattern och found_value kan upprepas så många gånger som önskas, vilket gör att olika värden kan returneras beroende på objektets värde. Mönstren kontrolleras i ordning, och den första matchningen returneras.
Alias: in_list(), list_contains()
list_item¶
list_item(value, index, separator) – interpret the value as a list of items separated by separator, returning the ’index’th item. The first item is number zero. The last item has the index -1 as in list_item(-1,separator). If the item is not in the list, then the empty string is returned. The separator has the same meaning as in the count function, usually comma but is ampersand for author-like lists.
select¶
select(value, key) – interpret the value as a comma-separated list of items with each item having the form id:id_value (the calibre identifier format). The function finds the first pair with the id equal to key and returns the corresponding id_value. If no id matches then the function returns the empty string.
str_in_list¶
str_in_list(value, separator, [string, found_val, ]+ not_found_val) – tolka value som en lista med objekt separerade med separator och jämför sedan string med varje värde i listan. string är inte ett reguljärt uttryck. Om string är lika med vilket objekt som helst (ignorerar gemener och versaler) returneras motsvarande found_val. Om string innehåller separators behandlas den också som en lista och varje delvärde kontrolleras. Paren string och found_value kan upprepas så många gånger som önskas, vilket gör att olika värden kan returneras beroende på strängens värde. Om ingen av strängarna matchar returneras not_found_value. Strängarna kontrolleras i ordning. Den första matchningen returneras.
Rekursion¶
eval¶
eval(sträng) – utvärderar strängen som ett program och skickar de lokala variablerna. Detta tillåter användning av mallprocessorn för att konstruera komplexa resultat från lokala variabler. I mallprogramläge, eftersom tecknen { och } tolkas innan mallen utvärderas, måste du använda [[ för tecknet { och ]] för tecknet }. De konverteras automatiskt. Observera också att prefix och suffix (syntaxen |prefix|suffix) inte kan användas i argumentet till den här funktionen när mallprogramläge används.
template¶
template(x) – utvärderar x som en mall. Utvärderingen görs i sitt eget sammanhang, vilket innebär att variabler inte delas mellan anroparen och mallutvärderingen. Om du inte använder allmänt programläge, eftersom { och } tecknen är speciella, måste du använda [[ för { tecknet och ]] för tecknet }; de konverteras automatiskt. Till exempel kommer template(\'[[title_sort]]\') att utvärdera mallen {title_sort} och returnera dess värde. Observera också att prefix och suffix (syntaxen |prefix|suffix) inte kan användas i argumentet till den här funktionen när du använder mallprogramläge.
Relationellt¶
cmp¶
cmp(value, y, lt, eq, gt) – compares value and y after converting both to numbers. Returns lt if value <# y, eq if value ==# y, otherwise gt. This function can usually be replaced with one of the numeric compare operators (==#, <#, >#, etc).
first_matching_cmp¶
first_matching_cmp(val, [ cmp, result, ]* else_result) – compares val < cmp in sequence, returning the associated result for the first comparison that succeeds. Returns else_result if no comparison succeeds.
Example:
i = 10;
first_matching_cmp(i,5,"small",10,"middle",15,"large","giant")
returns "large". The same example with a first value of 16 returns "giant".
strcmp¶
strcmp(x, y, lt, eq, gt) – gör en lexikal jämförelse av x och y utan att skiftläge känsligt. Returnerar lt om x < y, eq om x == y, annars gt. Denna funktion kan ofta ersättas av en av de lexikala jämförelseoperatorerna (==, >, <, etc.)
strcmpcase¶
strcmpcase(x, y, lt, eq, gt) – gör en skiftlägeskänslig lexikal jämförelse av x och y. Returnerar lt om x < y, eq om x == y, annars gt.
Obs: Detta är INTE standardbeteendet som används av calibre, till exempel i de lexikala jämförelseoperatorerna (==, >, <, etc.). Denna funktion kan orsaka oväntade resultat, använd helst strcmp() när det är möjligt.
Skiftlägesändringar¶
capitalize¶
capitalize(värde) – returnerar värdet med den första bokstaven i stor bokstav och resten i liten bokstav.
lowercase¶
lowercase(value) – returns the value in lower case.
titlecase¶
titlecase(värde) – returnerar värdet i titel/gemensam version.
uppercase¶
uppercase(value) – returnerar value med versaler.
Strängmanipulation¶
character¶
character(character_name) – returns the character named by character_name. For example, character('newline') returns a newline character ('\n'). The supported character names are newline, return, tab, and backslash. This function is used to put these characters into the output of templates.
check_yes_no¶
check_yes_no(field_name, is_undefined, is_false, is_true) – checks if the value of the yes/no field named by the lookup name field_name is one of the values specified by the parameters, returning 'Yes' if a match is found otherwise returning the empty string. Set the parameter is_undefined, is_false, or is_true to 1 (the number) to check that condition, otherwise set it to 0.
Example: check_yes_no("#bool", 1, 0, 1) returns 'Yes' if the yes/no field #bool is either True or undefined (neither True nor False).
More than one of is_undefined, is_false, or is_true can be set to 1.
contains¶
contains(value, pattern, text_if_match, text_if_not_match) – checks if the value is matched by the regular expression pattern. Returns text_if_match if the pattern matches the value, otherwise returns text_if_not_match.
field_exists¶
field_exists(lookup_name) – checks if a field (column) with the lookup name lookup_name exists, returning '1' if so and the empty string if not.
ifempty¶
ifempty(value, text_om_empty) – om värdet inte är tomt returnera då det value, annars returnera text_om_empty.
re¶
re(value, pattern, replacement) – return the value after applying the regular expression. All instances of pattern in the value are replaced with replacement. The template language uses case insensitive Python regular expressions.
re_group¶
re_group(value, pattern [, template_for_group]*) – return a string made by applying the regular expression pattern to value and replacing each matched instance with the value returned by the corresponding template. In Template Program Mode, like for the template and the eval functions, you use [[ for { and ]] for }.
The following example looks for a series with more than one word and uppercases the first word:
program: re_group(field('series'), "(\S* )(.*)", "{$:uppercase()}", "{$}")'}
shorten¶
shorten(value, left_chars, middle_text, right_chars) – Return a shortened version of the value, consisting of left_chars characters from the beginning of the value, followed by middle_text, followed by right_chars characters from the end of the value. left_chars and right_chars must be non-negative integers.
Example: assume you want to display the title with a length of at most 15 characters in length. One template that does this is {title:shorten(9,-,5)}. For a book with the title Ancient English Laws inthe Times of Ivanhoe the result will be Ancient E-anhoe: the first 9 characters of the title, a -, then the last 5 characters. If the value’s length is less than left chars + right chars + the length of middle text then the value will be returned unchanged. For example, the title TheDome would not be changed.
strcat¶
strcat(a[, b]*) – returnerar en sträng som bildas genom att sammanfoga alla argument. Kan ta valfritt antal argument. I de flesta fall kan du använda operatorn & istället för den här funktionen.
strcat_max¶
strcat_max(max, string1 [, prefix2, string2]*) – Returnerar en sträng som bildas genom att sammanfoga argumenten. Det returnerade värdet initieras till string1. Strängar som bildas av prefix, sträng-par läggs till i slutet av värdet så länge som den resulterande stränglängden är mindre än max. Prefix kan vara tomma. Returnerar string1 även om string2 är längre än max. Du kan skicka med så många prefix, sträng-par som du önskar.
strlen¶
strlen(value) – Returnerar längden på strängen value.
substr¶
substr(value, start, end) – returns the start’th through the end’th characters of value. The first character in value is the zero’th character. If end is negative then it indicates that many characters counting from the right. If end is zero, then it indicates the last character. For example, substr('12345', 1, 0) returns '2345', and substr('12345', 1, -1) returns '234'.
swap_around_articles¶
swap_around_articles(value, separator) – returnerar value med artiklar flyttade till slutet, separerade med semikolon. value kan vara en lista, i vilket fall varje objekt i listan bearbetas. Om value är en lista måste du ange separator. Om ingen separator anges eller om separatorn är en tom sträng behandlas value som ett enda värde, inte en lista. Articles är de som används av calibre för att generera title_sort.
swap_around_comma¶
swap_around_comma(value) – given a value of the form B, A, return A B. This is most useful for converting names in LN, FN format to FN LN. If there is no comma in the value then the function returns the value unchanged.
test¶
test(värde, text_if_not_empty, text_if_empty) – returnera text_if_not_empty om värdet inte är tomt, annars returnera text_if_empty.
transliterate¶
transliterate(value) – Returnerar en sträng i ett latinskt alfabet som bildas genom att approximera ljudet av orden i value. Till exempel, om value är Фёдор Миха́йлович Достоевский returnerar den här funktionen Fiodor Mikhailovich Dostoievskii.
URL-funktioner¶
encode_for_url¶
encode_for_url(value, use_plus) – returns the value encoded for use in a URL as specified by use_plus. The value is first URL-encoded. Next, if use_plus is 0 then spaces are replaced by '+' (plus) signs. If it is 1 then spaces are replaced by %20.
If you do not want the value to be encoding but to have spaces replaced then use the re() function, as in re($series, ' ', '%20')
See also the functions make_url(), make_url_extended() and query_string().
make_url¶
make_url(path, [query_name, query_value]+) – this function is the easiest way to construct a query URL. It uses a path, the web site and page you want to query, and query_name, query_value pairs from which the query is built. In general, the query_value must be URL-encoded. With this function it is always encoded and spaces are always replaced with '+' signs.
At least one query_name, query_value pair must be provided.
Example: constructing a Wikipedia search URL for the author Niccolò Machiavelli:
make_url('https://en.wikipedia.org/w/index.php', 'search', 'Niccolò Machiavelli')
returns
https://en.wikipedia.org/w/index.php?search=Niccol%C3%B2+Machiavelli
If you are writing a custom column book details URL template then use $item_name or field('item_name') to obtain the value of the field that was clicked on. Example: if Niccolò Machiavelli was clicked then you can construct the URL using:
make_url('https://en.wikipedia.org/w/index.php', 'search', $item_name)
See also the functions make_url_extended(), query_string() and encode_for_url().
make_url_extended¶
make_url_extended(...) – this function is similar to make_url() but gives you more control over the URL components. The components of a URL are
scheme:://authority/path?query string.
See Uniform Resource Locator on Wikipedia for more detail.
The function has two variants:
make_url_extended(scheme, authority, path, [query_name, query_value]+)
and
make_url_extended(scheme, authority, path, query_string)
This function returns a URL constructed from the scheme, authority, path, and either the query_string or a query string constructed from the query argument pairs. The authority can be empty, which is the case for calibre scheme URLs. You must supply either a query_string or at least one query_name, query_value pair. If you supply query_string and it is empty then the resulting URL will not have a query string section.
Example 1: constructing a Wikipedia search URL for the author Niccolò Machiavelli:
make_url_extended('https', 'en.wikipedia.org', '/w/index.php', 'search', 'Niccolò Machiavelli')
returns
https://en.wikipedia.org/w/index.php?search=Niccol%C3%B2+Machiavelli
See the query_string() function for an example using make_url_extended() with a query_string.
If you are writing a custom column book details URL template then use $item_name or field('item_name') to obtain the value of the field that was clicked on. Example: if Niccolò Machiavelli was clicked on then you can construct the URL using :
make_url_extended('https', 'en.wikipedia.org', '/w/index.php', 'search', $item_name')
See also the functions make_url(), query_string() and encode_for_url().
query_string¶
query_string([query_name, query_value, how_to_encode]+)– returnerar en URL-förfrågesträng konstruerad från triaderna query_name, query_value, how_to_encode. En förfrågesträng är en serie poster där varje post ser ut som query_name=query_value där query_value är URL-kodat enligt instruktionerna. Frågeobjekten är separerade med '&' (et-tecken).
Om how_to_encode är 0 kodas query_value och mellanslag ersätts med '+' (plus)-tecken. Om how_to_encode är 1 kodas query_value med mellanslag ersatta av %20. Om how_to_encode är 2 returneras query_value oförändrat; Ingen kodning görs och mellanslag ersätts inte. Om du vill att query_value inte ska kodas utan att mellanslag ska ersättas, använd då funktionen re(), som i re($series, ' ', '%20')
Du använder den här funktionen om du behöver specifik kontroll över hur delarna av frågesträngen är konstruerade. Du kan sedan använda den resulterande förfrågesträngen i make_url_extended(), som i
make_url_extended(
'https', 'your_host', 'your_path',
query_string('encoded', 'Hendrik Bäßler', 0, 'unencoded', 'Hendrik Bäßler', 2))
vilket ger dig
https://your_host/your_path?encoded=Hendrik+B%C3%A4%C3%9Fler&unencoded=Hendrik Bäßler
Du måste ha minst en query_name, query_value, how_to_encode-triad, men du kan ha så många du vill.
Det returnerade värdet är en URL-förfrågesträng med alla angivna objekt, till exempel: name1=val1[&nameN=valN]*. Observera att avgränsaren '?' path / query string inte ingår i det returnerade resultatet.
Om du skriver en anpassad URL-mall för kolumnbokdetaljer, använd $item_name eller field('item_name') för att hämta det okodade värdet för fältet som klickades på. Du har också item_value_quoted där värdet redan är kodat med plustecken som ersätter mellanslag, och item_value_no_plus där värdet redan är kodat med %20 som ersätter mellanslag.
Se även funktionerna make_url(), make_url_extended() och encode_for_url().
to_hex¶
to_hex(val) – returnerar strängen val kodad i hex. Detta är användbart när man konstruerar calibre-URL:er.
urls_from_identifiers¶
urls_from_identifiers(identifiers, sort_results) – given en kommaseparerad lista med identifiers, där en identifier är ett kolonsepar av värden (id_name:id_value), returnerar en kommaseparerad lista med HTML-URL:er genererade från identifierarna. Listan sorteras inte om sort_results är 0 (tecken eller siffra), annars sorteras den alfabetiskt efter identifierarens namn. URL:erna genereras på samma sätt som den inbyggda identifierarkolumnen när den visas i bokdetaljer.
Övriga¶
arguments¶
arguments(id[=expression] [, id[=expression]]*) – Används i en lagrad mall för att hämta argumenten som skickats i anropet. Den både deklarerar och initierar lokala variabler med de angivna namnen, id``s, vilket i praktiken gör dem till parametrar. Variablerna är positionella; de får värdet av argumentet som anges i anropet på samma position. Om motsvarande argument inte anges i anropet tilldelar ``arguments() variabeln det angivna standardvärdet. Om det inte finns något standardvärde sätts variabeln till den tomma strängen.
assign¶
assign(id, value) – tilldelar value till id och returnerar sedan value. id måste vara en identifierare, inte ett uttryck. I de flesta fall kan du använda operatorn = istället för den här funktionen.
globals¶
globals(id[=expression] [, id[=expression]]*) – Retrieves ”global variables” that can be passed into the formatter. The name id is the name of the global variable. It both declares and initializes local variables with the names of the global variables passed in the id parameters. If the corresponding variable is not provided in the globals then it assigns that variable the provided default value. If there is no default value then the variable is set to the empty string.
is_dark_mode¶
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
print¶
print(a [, b]*) – prints the arguments to standard output. Unless you start calibre from the command line (calibre-debug -g), the output will go into a black hole. The print function always returns its first argument.
set_globals¶
set_globals(id[=expression] [, id[=expression]]*) – Sets globalvariables that can be passed into the formatter. The globals are given the name of the id passed in. The value of the id is used unless an expression is provided.
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=('Okänd',), 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
