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.

Altro

arguments

class calibre.utils.formatter_functions.BuiltinArguments[sorgente]

arguments(id[=expression] [, id[=expression]]*) – Viene usata in un modello salvato per recuperare gli argomenti passati nella chiamata. Dichiara e inizializza le variabili locali con i nomi forniti, gli id, rendendoli di fatto parametri. Le variabili sono posizionali; prendono il valore dell’argomento fornito nella chiamata alla stessa posizione. Se l’argomento corrispondente non è fornito nella chiamata, arguments() assegna alla variabile il valore predefinito fornito. Se nessun valore predefinito è presente, la variabile è impostata a stringa vuota.

assign

class calibre.utils.formatter_functions.BuiltinAssign[sorgente]

assign(id, value) – assegna value a id, quindi restituisce value. id deve essere un identificatore, non un’espressione Nella maggior parte dei casi puoi usare l’operatore = invece di questa funzione.

globals

class calibre.utils.formatter_functions.BuiltinGlobals[sorgente]

globals(id[=expression] [, id[=expression]]*) – Recupera le «variabili globali» che possono essere passate alla funzione di formattazione. Il nome id è il nome della variabile globale. Dichiara e inizializza le variabili locali con i nomi delle variabili globali passate nei parametri id. Se la variabile corrispondente non è presente nelle variabili globali, assegna a quella variabile il valore predefinito fornito. Se non è presente alcun valore predefinito la variabile è impostata a stringa vuota.

is_dark_mode

class calibre.utils.formatter_functions.BuiltinIsDarkMode[sorgente]

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

class calibre.utils.formatter_functions.BuiltinPrint[sorgente]

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

class calibre.utils.formatter_functions.BuiltinSetGlobals[sorgente]

set_globals(id[=expression] [, id[=expression]]*) – Imposta delle variabili globali che possono essere passate alla funzione di formattazione. Queste variabili globali prendono il nome dell”id fornito. Viene usato il valore dell”id, a meno che non sia fornita un’espressione.

Aritmetiche

add

class calibre.utils.formatter_functions.BuiltinAdd[sorgente]

add(x [, y]*) – restituisce la somma dei suoi argomenti. Genera un’eccezione se un argomento non è un numero. Nella maggior parte dei casi puoi usare l’operatore + invece di questa funzione.

ceiling

class calibre.utils.formatter_functions.BuiltinCeiling[sorgente]

ceiling(value) – restituisce il più piccolo intero maggiore di o uguale a value. Genera un’eccezione se value non è un numero.

divide

class calibre.utils.formatter_functions.BuiltinDivide[sorgente]

divide(x, y) – restituisce x / y. Genera un’eccezione se x o y non sono numeri. Questa funzione può di solito essere sostituita dall’operatore /.

floor

class calibre.utils.formatter_functions.BuiltinFloor[sorgente]

floor(value) – restituisce il più grande intero minore di o uguale a value. Genera un’eccezione se value non è un numero.

fractional_part

class calibre.utils.formatter_functions.BuiltinFractionalPart[sorgente]

fractional_part(value) – restituisce la parte del valore dopo la virgola. Per esempio fractional_part(3.14) restituisce 0.14. Genera un’eccezione se value non è un numero.

mod

class calibre.utils.formatter_functions.BuiltinMod[sorgente]

mod(value, y) – restituisce il floor (intero inferiore più vicino) del resto di value / y. Genera un’eccezione se value o y non sono numeri.

multiply

class calibre.utils.formatter_functions.BuiltinMultiply[sorgente]

multiply(x [, y]*) – restituisce il prodotto dei suoi argomenti. Genera un’eccezione se uno dei suoi argomenti non è un numero. Questa funzione può spesso essere sostituita dall’operatore *.

round

class calibre.utils.formatter_functions.BuiltinRound[sorgente]

round(value) – restituisce l’intero più vicino a value. Genera un’eccezione se value non è un numero.

subtract

class calibre.utils.formatter_functions.BuiltinSubtract[sorgente]

subtract(x, y) – restituisce x - y. Genera un’eccezione se x o y non sono numeri. Questa funzione può spesso essere sostituita dall’operatore -.

Booleane

and

class calibre.utils.formatter_functions.BuiltinAnd[sorgente]

and(value [, value]*) – restituisce la stringa '1' se tutti i valori sono non vuoti, altrimenti restituisce una stringa vuota. Puoi fornire un numero arbitrario di valori. Nella maggior parte dei casi puoi usare l’operatore && invece di questa funzione. Una ragione per non sostituire and() con && si ha quando una valutazione in corto circuito («short-circuiting») può cambiare i risultati per via di effetti collaterali. Per esempio, and(a='',b=5) eseguirà sempre entrambi gli assegnamenti, mentre l’operatore && non eseguirà il secondo.

not

class calibre.utils.formatter_functions.BuiltinNot[sorgente]

not(value) – restituisce la stringa '1' se il valore è vuoto, altrimenti restituisce una stringa vuota. Questa funzione può di solito essere sostituita dall’operatore unario not (!).

or

class calibre.utils.formatter_functions.BuiltinOr[sorgente]

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.

Cambi di maiuscole

capitalize

class calibre.utils.formatter_functions.BuiltinCapitalize[sorgente]

capitalize(value) – restituisce value con la prima lettera maiuscola e il resto minuscolo.

lowercase

class calibre.utils.formatter_functions.BuiltinLowercase[sorgente]

lowercase(value) – restituisce value in minuscolo.

titlecase

class calibre.utils.formatter_functions.BuiltinTitlecase[sorgente]

titlecase(value) – restituisce value con le iniziali maiuscole.

uppercase

class calibre.utils.formatter_functions.BuiltinUppercase[sorgente]

uppercase(value) – restituisce value in maiuscolo.

Esaminazione di elenchi

identifier_in_list

class calibre.utils.formatter_functions.BuiltinIdentifierInList[sorgente]

identifier_in_list(val, nome_id [, val_trovato, val_non_trovato])tratta val come una lista di identificatori separati da virgola. Un identificatore ha la forma nome_id:valore. Il parametro nome_id è il testo nome_id che si vuole cercare, può essere nome_id oppure nome_id:regex. Nel primo caso si ha una corrispondenza se esiste un identificatore con il nome_id dato. Nel secondo caso si ha una corrispondenza se nome_id corrisponde e se il valore dell’identificatore corrisponde all’espressione regolare regex. Se val_trovato e val_non_trovato sono foniti, viene restituito val_trovato in caso di corrispondenza e val_non_trovato in caso contrario. Se invece non sono forniti, viene restituita la coppia identificatore:valore in caso di corrispondenza e una stringa vuota in caso contrario ('').

list_contains

class calibre.utils.formatter_functions.BuiltinInList[sorgente]

list_contains(value, separator, [ pattern, found_val, ]* not_found_val) – interpret the value as a list of items separated by separator, checking the pattern against each item in the list. If the pattern matches an item then return found_val, otherwise return not_found_val. The pair pattern and found_value can be repeated as many times as desired, permitting returning different values depending on the item’s value. The patterns are checked in order, and the first match is returned.

Aliases: in_list(), list_contains()

list_item

class calibre.utils.formatter_functions.BuiltinListitem[sorgente]

list_item(value, index, separator) – interpret the value as a list of items separated by separator, returning the “index’th item. The first item is number zero. The last item has the index -1 as in list_item(-1,separator). If the item is not in the list, then the empty string is returned. The separator has the same meaning as in the count function, usually comma but is ampersand for author-like lists.

select

class calibre.utils.formatter_functions.BuiltinSelect[sorgente]

select(value, key) – interpret the value as a comma-separated list of items with each item having the form id:id_value (the calibre identifier format). The function finds the first pair with the id equal to key and returns the corresponding id_value. If no id matches then the function returns the empty string.

str_in_list

class calibre.utils.formatter_functions.BuiltinStrInList[sorgente]

str_in_list(value, separator, [ string, found_val, ]+ not_found_val) – interpret the value as a list of items separated by separator then compare string against each value in the list. The string is not a regular expression. If string is equal to any item (ignoring case) then return the corresponding found_val. If string contains separators then it is also treated as a list and each subvalue is checked. The string and found_value pairs can be repeated as many times as desired, permitting returning different values depending on string’s value. If none of the strings match then not_found_value is returned. The strings are checked in order. The first match is returned.

Estrazione di valori dai metadati

annotation_count

class calibre.utils.formatter_functions.BuiltinAnnotationCount[sorgente]

annotation_count() – restituisce il numero totale di annotazioni di ogni tipo allegate al libro corrente. Questa funzione può essere usata solo nell’interfaccia grafica e nel server dei contenuti.

approximate_formats

class calibre.utils.formatter_functions.BuiltinApproximateFormats[sorgente]

approximate_formats() – restituisce una lista separata da virgole di formati associati al libro. Dato che la lista proviene dal database di calibre invece che dal file system, non c’è garanzia che questa lista sia corretta, sebbene probabilmente sia così. Tieni presente che i nomi di formato risultanti sono sempre in maiuscolo, come in EPUB. La funzione approximate_formats() è molto più rapida delle funzioni formats_....

Questa funzione può essere usata solo nell’interfaccia grafica. Se vuoi usare questi valori negli schemi di salvataggio su disco o di invio al dispositivo devi creare una «Colonna costruita da altre colonne» personalizzata, usare la funzione dello schema di quella colonna, e usare il valore di quella colonna nei tuoi schemi di salvataggio/invio.

author_sorts

class calibre.utils.formatter_functions.BuiltinAuthorSorts[sorgente]

author_sorts(val_separator) – restituisce una stringa contenente un elenco di valori di ordinamento autore per gli autori del libro. L’ordinamento è quello del che proviene dai dati dell’autore nei metadati, che può essere diverso dal valore di ordinamento dentro i libri. L’elenco è restituito nella forma author_sort 1 val_separator author_sort 2 ecc. senza spazi aggiunti. I valori di ordinamento autore di questo elenco sono nello stesso ordine degli autori del libro. Se desideri avere spazi ai lati di val_separator, includili nella stringa val_separator.

booksize

class calibre.utils.formatter_functions.BuiltinBooksize[sorgente]

booksize() – restituisce il valore del campo di calibre size. Restituisce “” se il libro non ha formati.

Questa funzione può essere usata solo nell’interfaccia grafica. Se vuoi usare questo valore negli schemi di salvataggio su disco o di invio al dispositivo devi creare una «Colonna costruita da altre colonne» personalizzata, usare la funzione dello schema di quella colonna, e usare il valore di quella colonna nei tuoi schemi di salvataggio/invio

connected_device_name

class calibre.utils.formatter_functions.BuiltinConnectedDeviceName[sorgente]

connected_device_name(storage_location_key) – se un dispositivo è connesso restituisce il suo nome, altrimenti restituisce una stringa vuota. Ognuna delle posizioni di memoria in un dispositivo ha il suo personale nome di dispositivo. I nomi per storage_location_key sono 'main', 'carda' e 'cardb'. Questa funzione può essere usata solo nell’interfaccia grafica.

connected_device_uuid

class calibre.utils.formatter_functions.BuiltinConnectedDeviceUUID[sorgente]

connected_device_uuid(storage_location_key) – se un dispositivo è connesso restituisce il suo uuid (id unico), altrimenti restituisce una stringa vuota. Ognuna delle posizioni di memoria in un dispositivo ha un uuid differente. I nomi delle posizioni per storage_location_key sono 'main', 'carda' e 'cardb'. Questa funzione può essere usata solo nell’interfaccia grafica.

current_library_name

class calibre.utils.formatter_functions.BuiltinCurrentLibraryName[sorgente]

current_library_name() – restituisce l’ultimo nome nel percorso della biblioteca di calibre corrente.

current_library_path

class calibre.utils.formatter_functions.BuiltinCurrentLibraryPath[sorgente]

current_library_path() – restituisce il percorso completo della biblioteca di calibre corrente.

current_virtual_library_name

class calibre.utils.formatter_functions.BuiltinCurrentVirtualLibraryName[sorgente]

current_virtual_library_name() – restituisce il nome della biblioteca virtuale corrente se ce n’è una, altrimenti una stringa vuota. Le maiuscole del nome della biblioteca sono conservate. Esempio:

program: current_virtual_library_name()

Questa funzione può essere usata solo nell’interfaccia grafica.

field

class calibre.utils.formatter_functions.BuiltinField[sorgente]

field(lookup_name) – restituisce il valore del campo di metadati con nome di riferimento lookup_name. Il prefisso $ può essere usato al posto della funzione, come in $tags.

formats_modtimes

class calibre.utils.formatter_functions.BuiltinFormatsModtimes[sorgente]

formats_modtimes(date_format_string) – restituisce una lista separata da virgole di elementi separati da due punti FMT:DATE che rappresentano le date di modifica dei formati di un libro. Il parametro date_format_string specifica quale sarà il formato della data. Vedi la funzione format_date() per dettagli. Puoi usare la funzione select() per ottenere la data di modifica di un formato specifico. Tieni presente che i nomi dei formati sono sempre in maiuscolo, come in EPUB.

formats_path_segments

class calibre.utils.formatter_functions.BuiltinFormatsPathSegments[sorgente]

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 Blogs

  • formats_path_segments(0, 0, 1, 1, '/') returns Help - Joe Blogs.epub

  • formats_path_segments(1, 0, 1, 1, '/') returns Joe Blogs/Help - Joe Blogs.epub

  • formats_path_segments(1, 0, 1, 0, '/') returns Joe Blogs/Help - Joe Blogs

  • formats_path_segments(0, 1, 0, 0, '/') returns Help - (calibre_id)

formats_paths

class calibre.utils.formatter_functions.BuiltinFormatsPaths[sorgente]

formats_paths([separator]) – return a separator-separated list of colon-separated items FMT:PATH giving the full path to the formats of a book. The separator argument is optional. If not supplied then the separator is ', ' (comma space). If the separator is a comma then 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[sorgente]

formats_sizes() – restituisce una lista separata da virgole di elementi separati da due punti FMT:SIZE che forniscono la dimensione dei formati di un libro in byte. Puoi usare la funzione select() per ottenere la dimensione di un formato specifico. Tieni presente che i nomi di formato sono sempre in maiuscolo, come in EPUB.

has_cover

class calibre.utils.formatter_functions.BuiltinHasCover[sorgente]

has_cover() – restituisce 'Yes' se il libro ha una copertina, altrimenti una stringa vuota.

is_marked

class calibre.utils.formatter_functions.BuiltinIsMarked[sorgente]

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

language_codes

class calibre.utils.formatter_functions.BuiltinLanguageCodes[sorgente]

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

language_strings

class calibre.utils.formatter_functions.BuiltinLanguageStrings[sorgente]

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

ondevice

class calibre.utils.formatter_functions.BuiltinOndevice[sorgente]

ondevice() – restituisce la stringa 'Yes' se ondevice è impostato, altrimenti restituisce una stringa vuota. Questa funzione può essere usata solo nell’interfaccia grafica. Se vuoi usare questo valore negli schemi di salvataggio su disco o di invio al dispositivo devi creare una «Colonna costruita da altre colonne» personalizzata, usare la funzione dello schema di quella colonna, e usare il valore di quella colonna nei tuoi schemi di salvataggio/invio.

raw_field

class calibre.utils.formatter_functions.BuiltinRawField[sorgente]

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

class calibre.utils.formatter_functions.BuiltinRawList[sorgente]

raw_list(nome_di_riferimento, separatore) – restituisce la lista di metadati identificata da nome_di_riferimento senza applicare alcuna formattazione od ordinamento, con gli elementi separati da separatore.

series_sort

class calibre.utils.formatter_functions.BuiltinSeriesSort[sorgente]

series_sort() – restituisce il valore di ordinamento serie.

user_categories

class calibre.utils.formatter_functions.BuiltinUserCategories[sorgente]

user_categories() – restituisce una lista separata da virgole delle categorie utente che contengono questo libro. Questa funzione può essere usata solo nell’interfaccia grafica. Se vuoi usare questi valori negli schemi di salvataggio su disco o di invio al dispositivo devi creare una Colonna costruita da altre colonne personalizzata, usare la funzione dello schema di quella colonna, e usare il valore di quella colonna nei tuoi schemi di salvataggio/invio

virtual_libraries

class calibre.utils.formatter_functions.BuiltinVirtualLibraries[sorgente]

virtual_libraries() – restituisce una lista separata da virgole delle Biblioteche Virtuali che contengono questo libro. Questa funzione può essere usata solo nell’interfaccia grafica. Se vuoi usare questi valori negli schemi di salvataggio su disco o di invio al dispositivo devi creare una Colonna costruita da altre colonne personalizzata, usare la funzione dello schema di quella colonna, e usare il valore di quella colonna nei tuoi schemi di salvataggio/invio.

Formattazione di valori

finish_formatting

class calibre.utils.formatter_functions.BuiltinFinishFormatting[sorgente]

finish_formatting(value, format, prefix, suffix) – apply the format, prefix, and suffix to the value in the same way as done in a template like {series_index:05.2f| - |- }. This function is provided to ease conversion of complex single-function- or template-program-mode templates to GPM Templates. For example, the following program produces the same output as the above template:

program: finish_formatting(field("series_index"), "05.2f", " - ", " - ")

Another example: for the template:

{series:re(([^\s])[^\s]+(\s|$),\1)}{series_index:0>2s| - | - }{title}

use:

program:
    strcat(
        re(field('series'), '([^\s])[^\s]+(\s|$)', '\1'),
        finish_formatting(field('series_index'), '0>2s', ' - ', ' - '),
        field('title')
    )

format_date

class calibre.utils.formatter_functions.BuiltinFormatDate[sorgente]

format_date(value, format_string) – format the value, which must be a date string, using the format_string, returning a string. It is best if the date is in ISO format as using other date formats often causes errors because the actual date value cannot be unambiguously determined. Note that the format_date_field() function is both faster and more reliable.

The formatting codes are:

  • d    : the day as number without a leading zero (1 to 31)

  • dd   : the day as number with a leading zero (01 to 31)

  • ddd  : the abbreviated localized day name (e.g. «Mon» to «Sun»)

  • dddd : the long localized day name (e.g. «Monday» to «Sunday»)

  • M    : the month as number without a leading zero (1 to 12)

  • MM   : the month as number with a leading zero (01 to 12)

  • MMM  : the abbreviated localized month name (e.g. «Jan» to «Dec»)

  • MMMM : the long localized month name (e.g. «January» to «December»)

  • yy   : the year as two digit number (00 to 99)

  • yyyy : the year as four digit number.

  • h    : the hours without a leading 0 (0 to 11 or 0 to 23, depending on am/pm)

  • hh   : the hours with a leading 0 (00 to 11 or 00 to 23, depending on am/pm)

  • m    : the minutes without a leading 0 (0 to 59)

  • mm   : the minutes with a leading 0 (00 to 59)

  • s    : the seconds without a leading 0 (0 to 59)

  • ss   : the seconds with a leading 0 (00 to 59)

  • ap   : use a 12-hour clock instead of a 24-hour clock, with “ap” replaced by the lowercase localized string for am or pm

  • AP   : use a 12-hour clock instead of a 24-hour clock, with “AP” replaced by the uppercase 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

  • Ap   : use a 12-hour clock instead of a 24-hour clock, with “Ap” replaced by the localized string for AM or PM

  • iso  : the date with time and timezone. Must be the only format present

  • to_number   : convert the date & time into a floating point number (a timestamp)

  • from_number : convert a floating point number (a timestamp) into an ISO-formatted date. If you want a different date format then add the desired formatting string after from_number and a colon (:). Example:

    format_date(val, 'from_number:MMM dd yyyy')
    

You might get unexpected results if the date you are formatting contains localized month names, which can happen if you changed the date format to contain MMMM. Using format_date_field() avoids this problem.

format_date_field

class calibre.utils.formatter_functions.BuiltinFormatDateField[sorgente]

format_date_field(field_name, format_string) – format the value in the field field_name, which must be the lookup name of a date field, either standard or custom. See format_date() for the formatting codes. This function is much faster than format_date() and should be used when you are formatting the value in a field (column). It is also more reliable because it works directly on the underlying date. It can’t be used for computed dates or dates in string variables. Examples:

format_date_field('pubdate', 'yyyy.MM.dd')
format_date_field('#date_read', 'MMM dd, yyyy')

format_duration

class calibre.utils.formatter_functions.BuiltinFormatDuration[sorgente]

format_duration(value, template, [largest_unit]) – format the value, a number of seconds, into a string showing weeks, days, hours, minutes, and seconds. If the value is a float then it is rounded to the nearest integer. You choose how to format the value using a template consisting of value selectors surrounded by [ and ] characters. The selectors are:

  • [w]: weeks

  • [d]: days

  • [h]: hours

  • [m]: minutes

  • [s]: seconds

You can put arbitrary text between selectors.

The following examples use a duration of 2 days (172,800 seconds) 1 hour (3,600 seconds) and 20 seconds, which totals to 176,420 seconds.

  • format_duration(176420, '[d][h][m][s]') will return the value 2d 1h 0m 20s.

  • format_duration(176420, '[h][m][s]') will return the value 49h 0m 20s.

  • format_duration(176420, 'Your reading time is [d][h][m][s]') returns the value Your reading time is 49h 0m 20s.

  • format_duration(176420, '[w][d][h][m][s]') will return the value 2d 1h 0m 20s. Note that the zero weeks value is not returned.

If you want to see zero values for items such as weeks in the above example, use an uppercase selector. For example, the following uses 'W' to show zero weeks:

format_duration(176420, '[W][d][h][m][s]') returns 0w 2d 1h 0m 20s.

By default the text following a value is the selector followed by a space. You can change that to whatever text you want. The format for a selector with your text is the selector followed by a colon followed by text segments separated by '|' characters. You must include any space characters you want in the output.

You can provide from one to three text segments.

  • If you provide one segment, as in [w: weeks ] then that segment is used for all values.

  • If you provide two segments, as in [w: weeks | week ] then the first segment is used for 0 and more than 1. The second segment is used for 1.

  • If you provide three segments, as in [w: weeks | week | weeks ] then the first segment is used for 0, the second segment is used for 1, and the third segment is used for more than 1.

The second form is equivalent to the third form in many languages.

For example, the selector:

  • [w: weeks | week | weeks ] produces '0 weeks ', '1 week ', or '2 weeks '.

  • [w: weeks | week ] produces '0 weeks ', '1 week ', or '2 weeks '.

  • [w: weeks ] produces 0 weeks ', 1 weeks ', or 2 weeks '.

The optional largest_unit parameter specifies the largest of weeks, days, hours, minutes, and seconds that will be produced by the template. It must be one of the value selectors. This can be useful to truncate a value.

format_duration(176420, '[h][m][s]', 'd') will return the value 1h 0m 20s instead of 49h 0m 20s.

format_number

class calibre.utils.formatter_functions.BuiltinFormatNumber[sorgente]

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

human_readable

class calibre.utils.formatter_functions.BuiltinHumanReadable[sorgente]

human_readable(value) – posto che value sia un numero, restituisce una stringa che rappresenta quel numero in KB, MB, GB, ecc.

rating_to_stars

class calibre.utils.formatter_functions.BuiltinRatingToStars[sorgente]

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.

Funzioni degli URL

encode_for_url

class calibre.utils.formatter_functions.BuiltinEncodeForURL[sorgente]

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

class calibre.utils.formatter_functions.BuiltinMakeUrl[sorgente]

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

class calibre.utils.formatter_functions.BuiltinMakeUrlExtended[sorgente]

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

class calibre.utils.formatter_functions.BuiltinQueryString[sorgente]

query_string([query_name, query_value, how_to_encode]+)– returns a URL query string constructed from the query_name, query_value, how_to_encode triads. A query string is a series of items where each item looks like query_name=query_value where query_value is URL-encoded as instructed. The query items are separated by '&' (ampersand) characters.

If how_to_encode is 0 then query_value is encoded and spaces are replaced with '+' (plus) signs. If how_to_encode is 1 then query_value is encoded with spaces replaced by %20. If how_to_encode is 2 then query_value is returned unchanged; no encoding is done and spaces are not replaced. If you want query_value not to be encoded but spaces to be replaced then use the re() function, as in re($series, ' ', '%20')

You use this function if you need specific control over how the parts of the query string are constructed. You could then use the resultingquery string in make_url_extended(), as in

make_url_extended(
       'https', 'your_host', 'your_path',
       query_string('encoded', 'Hendrik Bäßler', 0, 'unencoded', 'Hendrik Bäßler', 2))

giving you

https://your_host/your_path?encoded=Hendrik+B%C3%A4%C3%9Fler&unencoded=Hendrik Bäßler

You must have at least one query_name, query_value, how_to_encode triad, but can have as many as you wish.

The returned value is a URL query string with all the specified items, for example: name1=val1[&nameN=valN]*. Note that the '?' path / query string separator is not included in the returned result.

If you are writing a custom column book details URL template then use $item_name or field('item_name') to obtain the unencoded value of the field that was clicked. You also have item_value_quoted where the value is already encoded with plus signs replacing spaces, and item_value_no_plus where the value is already encoded with %20 replacing spaces.

See also the functions make_url(), make_url_extended() and encode_for_url().

to_hex

class calibre.utils.formatter_functions.BuiltinToHex[sorgente]

to_hex(val) – restituisce la stringa val codificata in esadecimale. Utile per costruire URL di calibre.

urls_from_identifiers

class calibre.utils.formatter_functions.BuiltinUrlsFromIdentifiers[sorgente]

urls_from_identifiers(identifiers, sort_results) – given a comma-separated list of identifiers, where an identifier is a colon-separated pair of values (id_name:id_value), returns a comma-separated list of HTML URLs generated from the identifiers. The list not sorted if sort_results is 0 (character or number), otherwise it is sorted alphabetically by the identifier name. The URLs are generated in the same way as the built-in identifiers column when shown in Book Details.

Funzioni di data

date_arithmetic

class calibre.utils.formatter_functions.BuiltinDateArithmetic[sorgente]

date_arithmetic(value, calc_spec, fmt) – Calcola una nuova data da value usando calc_spec. Restituisce la nuova data con formattazione fornita da fmt, opzionale: se non viene fornito, il risultato sarà in formato ISO. calc_spec è una stringa formata concatenando coppie di valori vT (valoreTipo) dove v è un numero, anche negativo, e T è una delle lettere seguenti:

  • s: aggiunge v secondi a date

  • m: aggiunge v minuti a date

  • h: aggiunge v ore a date

  • d: aggiunge v giorni a date

  • w: aggiunge v settimane a date

  • y: aggiunge v anni a date, dove un anno significa 365 giorni.

Esempio: '1s3d-1m' aggiungerà 1 secondo, poi 3 giorni, e infine sottrarrà 1 minuto da date.

days_between

class calibre.utils.formatter_functions.BuiltinDaysBetween[sorgente]

days_between(date1, date2) – restituisce il numero di giorni tra date1 e date2. Il numero è positivo se date1 è maggiore di date2, altrimenti è negativo. Se date1 o date2 non sono date, la funzione restituisce una stringa vuota.

today

class calibre.utils.formatter_functions.BuiltinToday[sorgente]

today() – return a date+time string for today (now). This value is designed for use in format_date or days_between, but can be manipulated like any other string. The date is in ISO date/time format.

Funzioni di database

book_count

class calibre.utils.formatter_functions.BuiltinBookCount[sorgente]

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

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

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

    program:
        vals = globals(vals='');
        if !vals then
            all_series = book_values('series', 'series:true', ',', 0);
            for series in all_series:
                if book_count('series:="' & series & '"', 0) == 1 then
                    vals = list_join(',', vals, ',', series, ',')
                fi
            rof;
            set_globals(vals)
        fi;
        str_in_list(vals, ',', $series, 1, '')
    

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

  • Use the stored template in a template search:

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

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

This function can be used only in the GUI and the content server.

book_values

class calibre.utils.formatter_functions.BuiltinBookValues[sorgente]

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

extra_file_modtime

class calibre.utils.formatter_functions.BuiltinExtraFileModtime[sorgente]

extra_file_modtime(file_name, format_string) – restituisce la data di modifica del file aggiuntivo file_name nella cartella data/ del libro se esiste, altrimenti -1. La data di modifica è formattata secondo format_string (vedi format_date() per dettagli). Se format_string è una stringa vuota, restituisce la data di modifica come numero di secondi in virgola mobile dall’inizio dell’epoca (epoch). Vedi anche le funzioni has_extra_files(), extra_file_names() e extra_file_size(). L’epoca dipende dal sistema operativo. Questa funzione può essere usata solo nell’interfaccia grafica e nel server dei contenuti.

extra_file_names

class calibre.utils.formatter_functions.BuiltinExtraFileNames[sorgente]

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

class calibre.utils.formatter_functions.BuiltinExtraFileSize[sorgente]

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.

get_note

class calibre.utils.formatter_functions.BuiltinGetNote[sorgente]

get_note(field_name, field_value, plain_text) – fetch the note for field field_name with value field_value. If plain_text is empty, return the note’s HTML including images. If plain_text is 1 (or '1'), return the note’s plain text. If the note doesn’t exist, return the empty string in both cases. Example:

  • Return the HTML of the note attached to the tag Fiction:

    program:
        get_note('tags', 'Fiction', '')
    
  • Return the plain text of the note attached to the author Isaac Asimov:

    program:
        get_note('authors', 'Isaac Asimov', 1)
    

This function works only in the GUI and the content server.

has_extra_files

class calibre.utils.formatter_functions.BuiltinHasExtraFiles[sorgente]

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

has_note

class calibre.utils.formatter_functions.BuiltinHasNote[sorgente]

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

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

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

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

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

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

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

This function works only in the GUI and the content server.

Iterazione su valori

first_non_empty

class calibre.utils.formatter_functions.BuiltinFirstNonEmpty[sorgente]

first_non_empty(value [, value]*) – restituisce il primo value non vuoto. Se tutti i valori sono vuoti, viene restituita una stringa vuota. Puoi avere un numero arbitrario di valori.

lookup

class calibre.utils.formatter_functions.BuiltinLookup[sorgente]

lookup(value, [ pattern, key, ]* else_key) – The patterns will be checked against the value in order. If a pattern matches then the value of the field named by key is returned. If no pattern matches then the value of the field named by else_key is returned. See also the switch() function.

switch

class calibre.utils.formatter_functions.BuiltinSwitch[sorgente]

switch(value, [patternN, valueN,]+ else_value) – for each patternN, valueN pair, checks if the value matches the regular expression patternN and if so returns the associated valueN. If no patternN matches, then else_value is returned. You can have as many patternN, valueN pairs as you wish. The first match is returned.

switch_if

class calibre.utils.formatter_functions.BuiltinSwitchIf[sorgente]

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.

Manipolazione di elenchi

list_count

class calibre.utils.formatter_functions.BuiltinCount[sorgente]

list_count(value, separator) – interpreta il valore come una lista di elementi separati da separator e restituisce il numero di elementi della lista. La maggior parte delle liste usa una virgola come separatore, ma authors usa la e commerciale (&).

Esempi: {tags:list_count(,)}, {authors:list_count(&)}.

Alias: count(), list_count()

list_count_field

class calibre.utils.formatter_functions.BuiltinFieldListCount[sorgente]

list_count_field(nome_di_riferimento) – restituisce il numero di elementi nel campo con nome di riferimento nome_di_riferimento. Il campo deve essere multivalore come ad esempio authors o tags, altrimenti la funzione darà luogo a un errore. Questa funzione è molto più veloce di list_count() perché opera direttamente su dati di calibre senza prima convertirli in una stringa. Esempio: list_count_field('tags').

list_count_matching

class calibre.utils.formatter_functions.BuiltinListCountMatching[sorgente]

list_count_matching(value, pattern, separator) – interpreta value come una lista di elementi separati da separator e restituisce il numero di elementi nella lista che corrispondono all’espressione regolare pattern.

Alias: list_count_matching(), count_matching()

list_difference

class calibre.utils.formatter_functions.BuiltinListDifference[sorgente]

list_difference(lista1, lista2, separatore) – restituisce una lista creata rimuovendo da lista1 tutti gli elementi trovati in lista2 facendo un confronto senza distinzione di maiuscole. Gli elementi in lista1 e lista2 sono separati da separatore, come anche gli elementi nella lista restituita.

list_equals

class calibre.utils.formatter_functions.BuiltinListEquals[sorgente]

list_equals(lista1, sep1, lista2, sep2, val_si, val_no) – restituisce val_si se lista1 e lista2 contengono gli stessi elementi, altrimenti restituisce val_no. Gli elementi sono determinati dividendo ogni lista usando il carattere separatore appropriato (sep1 o sep2). L’ordine degli elementi nelle liste non è rilevante. Il confronto non tiene conto delle maiuscole.

list_intersection

class calibre.utils.formatter_functions.BuiltinListIntersection[sorgente]

list_intersection(lista1, lista2, separatore) – restituisce una lista creata rimuovendo da lista1 tutti gli elementi non trovati in lista2 facendo un confronto senza distinzione di maiuscole. Gli elementi in lista1 e lista2 sono separati da separatore, come anche gli elementi nella lista restituita.

list_join

class calibre.utils.formatter_functions.BuiltinListJoin[sorgente]

list_join(with_separator, list1, separator1 [, list2, separator2]*) – return a list made by joining the items in the source lists (list1 etc) using with_separator between the items in the result list. Items in each source list[123...] are separated by the associated separator[123...]. A list can contain zero values. It can be a field like publisher that is single-valued, effectively a one-item list. Duplicates are removed using a case-insensitive comparison. Items are returned in the order they appear in the source lists. If items on lists differ only in letter case then the last is used. All separators can be more than one character.

Example:

program:
    list_join('#@#', $authors, '&', $tags, ',')

You can use list_join on the results of previous calls to list_join as follows:

program:
    a = list_join('#@#', $authors, '&', $tags, ',');
    b = list_join('#@#', a, '#@#', $#genre, ',', $#people, '&', 'some value', ',')

You can use expressions to generate a list. For example, assume you want items for authors and #genre, but with the genre changed to the word «Genre: « followed by the first letter of the genre, i.e. the genre «Fiction» becomes «Genre: F». The following will do that:

program:
    list_join('#@#', $authors, '&', list_re($#genre, ',', '^(.).*$', 'Genre: \1'),  ',')

list_re

class calibre.utils.formatter_functions.BuiltinListRe[sorgente]

list_re(src_list, separator, include_re, opt_replace) – Costruisce una lista, separando come prima cosa src_list in elementi singoli usando il carattere separator. Per ogni elemento nella lista, controlla se ha corrispondenze con include_re. Se ne ha, viene aggiunto alla lista da restituire. Se opt_replace non è una stringa vuota, applica la sostituzione prima di aggiungere l’elemento alla lista restituita.

list_re_group

class calibre.utils.formatter_functions.BuiltinListReGroup[sorgente]

list_re_group(src_list, separator, include_re, search_re [,template_for_group]*) – Come list_re() se non che le sostituzioni non sono opzionali. Usa re_group(item, search_re, template ...) per effettuare le sostituzioni.

list_remove_duplicates

class calibre.utils.formatter_functions.BuiltinListRemoveDuplicates[sorgente]

list_remove_duplicates(list, separator) – restituisce una lista creata rimuovendo gli elementi duplicati in list. Se gli elementi sono diversi solo per le maiuscole viene restituito l’ultimo elemento. Gli elementi in list sono separati da separator, come anche gli elementi nella lista restituita.

list_sort

class calibre.utils.formatter_functions.BuiltinListSort[sorgente]

list_sort(value, direction, separator) – return value sorted using a case-insensitive lexical sort. If direction is zero (number or character), value is sorted ascending, otherwise descending. The list items are separated by separator, as are the items in the returned list.

list_split

class calibre.utils.formatter_functions.BuiltinListSplit[sorgente]

list_split(elenca_val, sep, prefisso_id) – divide elenca_val in valori separati usando sep, poi assegna i valori a variabili locali con nome prefisso_id_N dove N è la posizione del valore nella lista. Il primo elemento ha posizione 0 (zero). La funzione restituisce l’ultimo elemento della lista.

Esempio:

list_split('uno:due:ciao', ':', 'var')

è equivalente a:

var_0 = 'uno'
    var_1 = 'due'
    var_2 = 'ciao'

list_union

class calibre.utils.formatter_functions.BuiltinListUnion[sorgente]

list_union(list1, list2, separator) – restituisce una lista creata unendo gli elementi di list1 e list2, rimuovendo gli elementi duplicati facendo un confronto senza distinzione di maiuscole. Se degli elementi sono diversi solo in termini di maiuscole, viene usato quello di list1. Gli elementi in list1 e list2 sono separati da separator, come anche gli elementi nella lista restituita.

Alias: merge_lists(), list_union()

range

class calibre.utils.formatter_functions.BuiltinRange[sorgente]

range(start, stop, step, limit) – returns a list of numbers generated by looping over the range specified by the parameters start, stop, and step, with a maximum length of limit. The first value produced is “start”. Subsequent values next_v = current_v + step. The loop continues while next_v < stop assuming step is positive, otherwise while next_v > stop. An empty list is produced if start fails the test: start >= stop if step is positive. The limit sets the maximum length of the list and has a default of 1000. The parameters start, step, and limit are optional. Calling range() with one argument specifies stop. Two arguments specify start and stop. Three arguments specify start, stop, and step. Four arguments specify start, stop, step and limit.

Examples:

range(5) -> '0, 1, 2, 3, 4'
range(0, 5) -> '0, 1, 2, 3, 4'
range(-1, 5) -> '-1, 0, 1, 2, 3, 4'
range(1, 5) -> '1, 2, 3, 4'
range(1, 5, 2) -> '1, 3'
range(1, 5, 2, 5) -> '1, 3'
range(1, 5, 2, 1) -> error(limit exceeded)

subitems

class calibre.utils.formatter_functions.BuiltinSubitems[sorgente]

subitems(value, start_index, end_index) – This function breaks apart lists of tag-like hierarchical items such as genres. It interprets the value as a comma- separated list of tag-like items, where each item is a period-separated list. It returns a new list made by extracting from each item the components from start_index to end_index, then merging the results back together. Duplicates are removed. The first subitem in a period-separated list has an index of zero. If an index is negative then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list.

Examples:

  • Assuming a #genre column containing «A.B.C»:

    • {#genre:subitems(0,1)} returns «A»

    • {#genre:subitems(0,2)} returns «A.B»

    • {#genre:subitems(1,0)} returns «B.C»

  • Assuming a #genre column containing «A.B.C, D.E»:

    • {#genre:subitems(0,1)} returns «A, D»

    • {#genre:subitems(0,2)} returns «A.B, D.E»

sublist

class calibre.utils.formatter_functions.BuiltinSublist[sorgente]

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»

Manipolazione di stringhe

character

class calibre.utils.formatter_functions.BuiltinCharacter[sorgente]

character(character_name) – restituisce il carattere di nome nome_carattere. Per esempio, character('newline') restituisce un carattere nuova riga ('\n'). I nomi di carattere supportati sono newline, return, tab, e backslash. Questa funzione è usata per inserire questi caratteri nel risultato dei modelli.

check_yes_no

class calibre.utils.formatter_functions.BuiltinCheckYesNo[sorgente]

check_yes_no(field_name, is_undefined, is_false, is_true) – controlla se il valore del campo sì/no il cui nome di riferimento è field_name è uno dei valori specificati dai parametri, restituisce 'Yes' se viene trovata una corrispondenza, altrimenti restituisce una stringa vuota. Imposta uno dei parametri is_undefined, is_false o is_true a 1 (numero) per effettuare il controllo su quella condizione, altrimenti impostalo su 0.

Esempio: check_yes_no("#bool", 1, 0, 1) restituisce 'Yes' se il campo sì/no «#bool» non è definito (né True né False) oppure se è True.

Più di una condizione tra is_undefined, is_false e is_true può essere impostata a 1.

contains

class calibre.utils.formatter_functions.BuiltinContains[sorgente]

contains(value, pattern, text_if_match, text_if_not_match) – controlla se il valore contiene corrispondenze per l’espressione regolare pattern. Restituisce text_if_match se vengono trovati dei risultati, altrimenti restituisce text_if_not_match.

field_exists

class calibre.utils.formatter_functions.BuiltinFieldExists[sorgente]

field_exists(lookup_name) – controlla se esiste un campo (colonna) con il nome di riferimento lookup_name, restituendo '1' se esiste e una stringa vuota se non esiste.

ifempty

class calibre.utils.formatter_functions.BuiltinIfempty[sorgente]

ifempty(value, text_if_empty) – se value non è vuota restituisce value, altrimenti restituisce text_if_empty.

re

class calibre.utils.formatter_functions.BuiltinRe[sorgente]

re(value, pattern, replacement) – return the value after applying the regular expression. All instances of pattern in the value are replaced with replacement. The template language uses case insensitive Python regular expressions.

re_group

class calibre.utils.formatter_functions.BuiltinReGroup[sorgente]

re_group(value, pattern [, template_for_group]*) – return a string made by applying the regular expression pattern to value and replacing each matched instance with the value returned by the corresponding template. In Template Program Mode, like for the template and the eval functions, you use [[ for { and ]] for }.

The following example looks for a series with more than one word and uppercases the first word:

program: re_group(field('series'), "(\S* )(.*)", "{$:uppercase()}", "{$}")'}

shorten

class calibre.utils.formatter_functions.BuiltinShorten[sorgente]

shorten(value, left_chars, middle_text, right_chars) – Return a shortened version of the value, consisting of left_chars characters from the beginning of the value, followed by middle_text, followed by right_chars characters from the end of the value. left_chars and right_chars must be non-negative integers.

Example: assume you want to display the title with a length of at most 15 characters in length. One template that does this is {title:shorten(9,-,5)}. For a book with the title Ancient English Laws inthe Times of Ivanhoe the result will be Ancient E-anhoe: the first 9 characters of the title, a -, then the last 5 characters. If the value’s length is less than left chars + right chars + the length of middle text then the value will be returned unchanged. For example, the title TheDome would not be changed.

strcat

class calibre.utils.formatter_functions.BuiltinStrcat[sorgente]

strcat(a [, b]*) – returns a string formed by concatenating all the arguments. Can take any number of arguments. In most cases you can use the & operator instead of this function.

strcat_max

class calibre.utils.formatter_functions.BuiltinStrcatMax[sorgente]

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

strlen

class calibre.utils.formatter_functions.BuiltinStrlen[sorgente]

strlen(value) – Restituisce la lunghezza della stringa value.

substr

class calibre.utils.formatter_functions.BuiltinSubstr[sorgente]

substr(value, start, end) – restituisce i caratteri di value da «start» a «end». Il primo carattere in value è il carattere zero. Se end è un numero negativo, indica quel numero di caratteri contando da destra. Se end è zero, indica l’ultimo carattere. Ad esempio, substr('12345', 1, 0) restituisce '2345' e substr('12345', 1, -1) restituisce '234'.

swap_around_articles

class calibre.utils.formatter_functions.BuiltinSwapAroundArticles[sorgente]

swap_around_articles(value, separator) – returns the value with articles moved to the end, separated by a semicolon. The value can be a list, in which case each item in the list is processed. If the value is a list then you must provide the separator. If no separator is provided or the separator is the empty string then the value is treated as being a single value, not a list. The articles are those used by calibre to generate the title_sort.

swap_around_comma

class calibre.utils.formatter_functions.BuiltinSwapAroundComma[sorgente]

swap_around_comma(value) – given a value of the form B, A, return A B. This is most useful for converting names in LN, FN format to FN LN. If there is no comma in the value then the function returns the value unchanged.

test

class calibre.utils.formatter_functions.BuiltinTest[sorgente]

test(value, text_if_not_empty, text_if_empty) – restituisce text_if_not_empty se il valore non è vuoto, altrimenti restituisce text_if_empty.

transliterate

class calibre.utils.formatter_functions.BuiltinTransliterate[sorgente]

transliterate(value) – Restituisce una stringa in alfabeto latino creata in modo da approssimare il suono delle parole in value. Per esempio, se value è Фёдор Миха́йлович Достоевский questa funzione restituisce Fiodor Mikhailovich Dostoievskii.

Relazionali

cmp

class calibre.utils.formatter_functions.BuiltinCmp[sorgente]

cmp(value, y, lt, eq, gt) – confronta value e y dopo aver convertito entrambi in numeri. Restituisce lt se value <# y, eq se value ==# y, altrimenti gt. Questa funzione può di solito essere sostituita con uno degli operatori numerici di confronto (==#, <#, >#, ecc).

first_matching_cmp

class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp[sorgente]

first_matching_cmp(val, [ cmp, result, ]* else_result) – confronta val < cmp in sequenza, restituendo il relativo result per il primo confronto che ha successo. Restituisce else_result se nessun confronto ha successo.

Esempio:

i = 10;
first_matching_cmp(i,5,"piccolo",10,"medio",15,"grande","gigante")

restituisce "grande". Lo stesso esempio con 16 come primo valore restituisce "gigante".

strcmp

class calibre.utils.formatter_functions.BuiltinStrcmp[sorgente]

strcmp(x, y, lt, eq, gt) – effettua un confronto lessicale senza distinguere tra maiuscole e minuscole di x e y. Restituisce lt se x < y, eq se x == y, altrimenti gt. Questa funzione può spesso essere sostituita da uno degli operatori lessicali di confronto (==, >, <, ecc.)

strcmpcase

class calibre.utils.formatter_functions.BuiltinStrcmpcase[sorgente]

strcmpcase(x, y, lt, eq, gt) – confronta x e y, distinguendo tra maiuscole e minuscole. Restituisce lt se x < y, eq se x == y, altrimenti restituisce gt.

Nota bene: Questo NON È il conportamento predefinito applicato da calibre, per esempio, negli operatori lessicali di confronto (==, >, <, ecc.). Questa funzione potrebbe portare a risultati inaspettati, sarebbe meglio usare strcmp() dove possibile.

Ricorsive

eval

class calibre.utils.formatter_functions.BuiltinEval[sorgente]

eval(string) – evaluates the string as a program, passing the local variables. This permits using the template processor to construct complex results from local variables. In Template Program Mode, because the { and } characters are interpreted before the template is evaluated 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

class calibre.utils.formatter_functions.BuiltinTemplate[sorgente]

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. If not using General Program Mode, 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.

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

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

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

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

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

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

set_identifier(typ, val)[sorgente]

If val is empty, deletes identifier of type typ

standard_field_keys()[sorgente]

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

custom_field_keys()[sorgente]

return a list of the custom fields in this book

all_field_keys()[sorgente]

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

metadata_for_field(key)[sorgente]

return metadata describing a standard or custom field.

all_non_none_fields()[sorgente]

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

get_standard_metadata(field, make_copy)[sorgente]

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

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

get_all_user_metadata(make_copy)[sorgente]

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

get_user_metadata(field, make_copy)[sorgente]

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

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

set_user_metadata(field, metadata)[sorgente]

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

remove_stale_user_metadata(other_mi)[sorgente]

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

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

Merge the information in other into self. In case of conflicts, the information in other takes precedence, unless the information in other is NULL.

format_field(key, series_with_index=True)[sorgente]

Returns the tuple (display_name, formatted_value)

to_html()[sorgente]

A HTML representation of this object.

calibre.ebooks.metadata.book.base.STANDARD_METADATA_FIELDS

The set of standard metadata fields.


'''
All fields must have a NULL value represented as None for simple types,
an empty list/dictionary for complex types and (None, None) for cover_data
'''

SOCIAL_METADATA_FIELDS = frozenset((
    'tags',             # Ordered list
    'rating',           # A floating point number between 0 and 10
    'comments',         # A simple HTML enabled string
    'series',           # A simple string
    'series_index',     # A floating point number
    # Of the form { scheme1:value1, scheme2:value2}
    # For example: {'isbn':'123456789', 'doi':'xxxx', ... }
    'identifiers',
))

'''
The list of names that convert to identifiers when in get and set.
'''

TOP_LEVEL_IDENTIFIERS = frozenset((
    'isbn',
))

PUBLICATION_METADATA_FIELDS = frozenset((
    'title',            # title must never be None. Should be _('Unknown')
    # Pseudo field that can be set, but if not set is auto generated
    # from title and languages
    'title_sort',
    'authors',          # Ordered list. Must never be None, can be [_('Unknown')]
    'author_sort_map',  # Map of sort strings for each author
    # Pseudo field that can be set, but if not set is auto generated
    # from authors and languages
    'author_sort',
    'book_producer',
    'timestamp',        # Dates and times must be timezone aware
    'pubdate',
    'last_modified',
    'rights',
    # So far only known publication type is periodical:calibre
    # If None, means book
    'publication_type',
    'uuid',             # A UUID usually of type 4
    'languages',        # ordered list of languages in this publication
    'publisher',        # Simple string, no special semantics
    # Absolute path to image file encoded in filesystem_encoding
    'cover',
    # Of the form (format, data) where format is, e.g. 'jpeg', 'png', 'gif'...
    'cover_data',
    # Either thumbnail data, or an object with the attribute
    # image_path which is the path to an image file, encoded
    # in filesystem_encoding
    'thumbnail',
))

BOOK_STRUCTURE_FIELDS = frozenset((
    # These are used by code, Null values are None.
    'toc', 'spine', 'guide', 'manifest',
))

USER_METADATA_FIELDS = frozenset((
    # A dict of dicts similar to field_metadata. Each field description dict
    # also contains a value field with the key #value#.
    'user_metadata',
))

DEVICE_METADATA_FIELDS = frozenset((
    'device_collections',   # Ordered list of strings
    'lpath',                # Unicode, / separated
    'size',                 # In bytes
    'mime',                 # Mimetype of the book file being represented
))

CALIBRE_METADATA_FIELDS = frozenset((
    'application_id',   # An application id, currently set to the db_id.
    'db_id',            # the calibre primary key of the item.
    'formats',          # list of formats (extensions) for this book
    # a dict of user category names, where the value is a list of item names
    # from the book that are in that category
    'user_categories',
    # a dict of items to associated hyperlink
    'link_maps',
))

ALL_METADATA_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           USER_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# All fields except custom fields
STANDARD_METADATA_FIELDS = SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# Metadata fields that smart update must do special processing to copy.
SC_FIELDS_NOT_COPIED =     frozenset(('title', 'title_sort', 'authors',
                                      'author_sort', 'author_sort_map',
                                      'cover_data', 'tags', 'languages',
                                      'identifiers'))

# Metadata fields that smart update should copy only if the source is not None
SC_FIELDS_COPY_NOT_NULL =  frozenset(('device_collections', 'lpath', 'size', 'comments', 'thumbnail'))

# Metadata fields that smart update should copy without special handling
SC_COPYABLE_FIELDS =       SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS) - \
                           SC_FIELDS_NOT_COPIED.union(
                           SC_FIELDS_COPY_NOT_NULL)

SERIALIZABLE_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           USER_METADATA_FIELDS).union(
                           PUBLICATION_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS) - \
                           frozenset(('device_collections', 'formats',
                               'cover_data'))
# these are rebuilt when needed