calibre User Manual
Release 7.19.0
Kovid Goyal
September 27, 2024
CONTENTS
1 The Graphical User Interface 3
2 Adding your favorite news website 31
3 The E-book viewer 51
4 E-book conversion 59
5 Editing e-books 79
6 The calibre Content server 113
7 Comparing e-books 121
8 Editing e-book metadata 125
9 Frequently Asked Questions 129
10 Tutorials 153
11 The calibre:// URL scheme 253
12 Customizing calibre 257
13 Command Line Interface 303
14 Setting up a calibre development environment 361
15 Digital Rights Management (DRM) 391
16 Glossary 393
Python Module Index 395
Index 397
i
ii
calibre User Manual, Release 7.19.0
calibre is an e-book library manager. It can view, convert and catalog e-books in most of the major e-book formats. It can
also talk to many e-book reader devices. It can go out to the Internet and fetch metadata for your books. It can download
newspapers and convert them into e-books for convenient reading. It is cross platform, running on Linux, Windows and
macOS.
You’ve just started calibre. What do you do now? Before calibre can do anything with your e-books, it rst has to know
about them. Drag and drop a few e-book les into calibre, or click the “Add books” button and browse for the e-books
you want to work with. Once you’ve added the books, they will show up in the main view looking something like this:
Once you’ve admired the list of books you just added to your heart’s content, you’ll probably want to read one. In order
to do that you’ll have to convert the book to a format your reader understands. When rst running calibre, the Welcome
wizard starts and will set up calibre for your reader device. Conversion is a breeze. Just select the book you want to convert
then click the “Convert books” button. Ignore all the options for now and click “OK”. The little icon in the bottom right
corner will start spinning. Once it’s nished spinning, your converted book is ready. Click the “View” button to read the
book.
If you want to read the book on your reader, connect the reader to the computer, wait till calibre detects it (10-20 seconds)
and then click the “Send to device” button. Once the icon stops spinning again, disconnect your reader and read away! If
you didn’t convert the book in the previous step, calibre will auto convert it to the format your reader device understands.
To get started with more advanced usage, you should read about The Graphical User Interface (page 3). For even more
power and versatility, learn the Command Line Interface (page 303). You will nd the list of Frequently Asked Questions
(page 129) useful as well.
If you have more questions, or want to discuss calibre with other users or ask for help with specic things, there are forums
and other help resources available
1
.
Sections
1
https://calibre-ebook.com/help
CONTENTS 1
calibre User Manual, Release 7.19.0
2 CONTENTS
CHAPTER
ONE
THE GRAPHICAL USER INTERFACE
The Graphical User Interface (GUI) provides access to all library management and e-book format conversion features.
The basic workow for using calibre is to rst add books to the library from your hard disk. calibre will automatically try
to read metadata from the books and add them to its internal database. Once they are in the database, you can perform
various Actions (page 4) on them that include conversion from one format to another, transfer to the reading device,
viewing on your computer, and editing metadata. The latter includes modifying the cover, description, and tags among
other details. Note that calibre creates copies of the les you add to it. Your original les are left untouched.
The interface is divided into various sections:
Actions (page 4)
Preferences (page 10)
Catalogs (page 11)
Search & sort (page 11)
The search interface (page 12)
Saving searches (page 18)
Searching the full text of all books (page 18)
Virtual libraries (page 19)
Temporarily marking books (page 19)
Guessing metadata from le names (page 19)
Book details (page 20)
Tag browser (page 22)
Cover grid (page 24)
Cover browser (page 25)
Adding notes for authors, series, etc. (page 26)
Quickview (page 27)
Jobs (page 28)
Keyboard shortcuts (page 28)
3
calibre User Manual, Release 7.19.0
1.1 Actions
The actions toolbar provides convenient shortcuts to commonly used actions. If you right-click the buttons, you can
perform variations on the default action. Please note that the actions toolbar will look slightly dierent depending on
whether you have an e-book reader attached to your computer.
Add books (page 4)
Edit metadata (page 5)
Convert books (page 6)
View (page 6)
Send to device (page 6)
Fetch news (page 7)
Library (page 7)
Device (page 8)
Save to disk (page 9)
Connect/share (page 9)
Remove books (page 10)
1.1.1 Add books
The Add books action has seven variations accessed by doing a right-click on the button.
1. Add books from a single folder: Opens a le chooser dialog and allows you to specify which books in a folder
should be added. This action is context sensitive, i.e. it depends on which catalog (page 11) you have selected. If
you have selected the Library, books will be added to the library. If you have selected the e-book reader device,
the books will be uploaded to the device, and so on.
2. Add books from folders and sub-folders: Allows you to choose a folder. The folder and all its sub-folders are
scanned recursively, and any e-books found are added to the library. You can choose whether to have calibre add
all les present in a single folder to a single book record or multiple book records. calibre assumes that each folder
contains a single book. All e-book les in a folder are assumed to be the same book in dierent formats. This
action is the inverse of the Save to disk (page 9) action, i.e. you can Save to disk, delete the books and re-add them
in single book per folder mode, with no lost information except for the date (this assumes you have not changed
any of the setting for the Save to disk action).
3. Add multiple books from archive (ZIP/RAR): Allows you to add multiple e-books that are stored inside the
selected ZIP or RAR les. It is a convenient shortcut that avoids having to rst unzip the archive and then add the
4 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
books via one of the above two options.
4. Add empty book (Book Entry with no formats): Allows you to create a blank book record. This can be used to
then manually ll out the information about a book that you may not have yet in your collection.
5. Add from ISBN: Allows you to add one or more books by entering their ISBNs.
6. Add les to selected book records: Allows you to add or update the les associated with an existing book in your
library.
7. Add data les to selected book records: Allows you to add any number of extra les that will be stored in a data
sub-directory in the book directory. See Adding extra data les to a book (page 128) for details.
8. Add an empty le to selected book records: Allows you to add an empty le of the specied format to the
selected book records.
The Add books action can read metadata from a wide variety of e-book formats. In addition, it tries to guess metadata
from the lename. See the Guessing metadata from le names (page 19) section, to learn how to congure this.
To add an additional format for an existing book you can do any of three things:
1. Drag and drop the le onto the Book details panel on the right side of the main window
2. Right click the Add books button and choose Add les to selected books.
3. Click the Add books button in the top right area of the Edit metadata dialog, accessed by the Edit metadata (page 5)
action.
1.1.2 Edit metadata
The Edit metadata action has four variations which can be accessed by doing a right-click on the
button.
1. Edit metadata individually: Allows you to edit the metadata of books one-by-one with the option of fetching
metadata, including covers, from the Internet. It also allows you to add or remove particular e-book formats from
a book.
2. Edit metadata in bulk: Allows you to edit common metadata elds for large numbers of books simultaneously.
It operates on all the books you have selected in the Library view (page 11).
3. Download metadata and covers: Downloads metadata and covers (if available) for the books that are selected in
the book list.
4. Merge book records: Gives you the capability of merging the metadata and formats of two or more book records.
You can choose to either delete or keep the records that were not clicked rst.
5. Manage data les: Manage the extra data les associated with the selected books.
For more details, see Editing e-book metadata (page 125).
1.1. Actions 5
calibre User Manual, Release 7.19.0
1.1.3 Convert books
E-books can be converted from a number of formats into whatever format your e-book reader
prefers. Many e-books available for purchase will be protected by Digital Rights Management (page 391) (DRM) technol-
ogy. calibre will not convert these e-books. It is easy to remove the DRM from many formats, but as this may be illegal,
you will have to nd tools to liberate your books yourself and then use calibre to convert them.
For most people, conversion should be a simple one-click aair. If you want to learn more about the conversion process,
see E-book conversion (page 59).
The Convert books action has three variations, accessed by doing a right-click on the button.
1. Convert individually: Allows you to specify conversion options to customize the conversion of each selected
e-book.
2. Bulk convert: Allows you to specify options only once to convert a number of e-books in bulk.
3. Create a catalog of the books in your calibre library: Allows you to generate a complete listing of the books
in your library, including all metadata, in several formats such as XML, CSV, BiBTeX, EPUB and MOBI. The
catalog will contain all the books currently showing in the library view. This allows you to use the search features
to limit the books to be catalogued. In addition, if you select multiple books using the mouse, only those books will
be added to the catalog. If you generate the catalog in an e-book format such as EPUB, MOBI or AZW3, the next
time you connect your e-book reader the catalog will be automatically sent to the device. For more information on
how catalogs work, read the Creating AZW3 EPUB MOBI catalogs (page 244).
1.1.4 View
The View action displays the book in an e-book viewer program. calibre has a built-in viewer for many
e-book formats. For other formats it uses the default operating system application. You can congure which formats
should open with the internal viewer via Preferences → Interface → Behavior. If a book has more than one format, you
can view a particular format by doing a right-click on the button.
1.1.5 Send to device
The Send to device action has eight variations, accessed by doing a right-click on the button.
1. Send to main memory: The selected books are transferred to the main memory of the e-book reader.
2. Send to card (A): The selected books are transferred to the storage card (A) on the e-book reader.
6 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
3. Send to card (B): The selected books are transferred to the storage card (B) on the e-book reader.
4. Send specic format to: The selected books are transferred to the selected storage location on the device, in the
format that you specify.
5. Eject device: Detaches the device from calibre.
6. Set default send to device action: Allows you to specify which of the options, 1 through 5 above or 7 below, will
be the default action when you click the main button.
7. Send and delete from library: The selected books are transferred to the selected storage location on the device
and then deleted from the Library.
8. Fetch Annotations (experimental): Transfers annotations you may have made on an e-book on your device to
the comments metadata of the book in the calibre library.
You can control the le name and folder structure of les sent to the device by setting up a template in Prefer-
ences → Import/export → Sending books to devices. Also see The calibre template language (page 161).
1.1.6 Fetch news
The Fetch news action downloads news from various websites and converts it into an e-book that can
be read on your e-book reader. Normally, the newly created e-book is added to your e-book library, but if an e-book
reader is connected at the time the download nishes, the news is also uploaded to the reader automatically.
The Fetch news action uses simple recipes (10-15 lines of code) for each news site. To learn how to create recipes for
your own news sources, see Adding your favorite news website (page 31).
The Fetch news action has three variations, accessed by doing a right-click on the button.
1. Schedule news download: Allows you to schedule the download of your selected news sources from a list of
hundreds available. Scheduling can be set individually for each news source you select and the scheduling is exible
allowing you to select specic days of the week or a frequency of days between downloads.
2. Add a custom news source: Allows you to create a simple recipe for downloading news from a custom news site
that you wish to access. Creating the recipe can be as simple as specifying an RSS news feed URL, or you can
be more prescriptive by creating Python-based code for the task. For more information, see Adding your favorite
news website (page 31).
3. Download all scheduled news sources: Causes calibre to immediately begin downloading all news sources that
you have scheduled.
1.1.7 Library
The Library action allows you to create, switch between, rename or remove a Library. calibre allows
you to create as many libraries as you wish. You could, for instance, create a ction library, a non-ction library, a foreign
1.1. Actions 7
calibre User Manual, Release 7.19.0
language library, a project library, or any structure that suits your needs. Libraries are the highest organizational structure
within calibre. Each library has its own set of books, tags, categories and base storage location.
1. Switch/create library…: Allows you to; a) connect to a pre-existing calibre library at another location, b) create
an empty library at a new location or, c) move the current library to a newly specied location.
2. Quick switch: Allows you to switch between libraries that have been registered or created within calibre.
3. Rename library: Allows you to rename a Library.
4. Pick a random book: Chooses a random book in the library for you
5. Remove library: Allows you to unregister a library from calibre.
6. Export/import all calibre data: Allows you to either export calibre data for migration to a new computer or
import previously exported data.
7. <library name>: Actions 7, 8 etc… give you immediate switch access between multiple libraries that you have
created or attached to. This list contains only the 5 most frequently used libraries. For the complete list, use the
Quick Switch menu.
8. Library maintenance
: Allows you to check the current library for data consistency issues and restore the current
library’s database from backups.
® Note
Metadata about your e-books, e.g. title, author, and tags, is stored in a single le in your calibre library folder
called metadata.db. If this le gets corrupted (a very rare event), you can lose the metadata. Fortunately, calibre
automatically backs up the metadata for every individual book in the book’s folder as an OPF le. By using the
Restore database action under Library Maintenance described above, you can have calibre rebuild the metadata.db
le from the individual OPF les for you.
You can copy or move books between dierent libraries (once you have more than one library setup) by right clicking on
the book and selecting the action Copy to library.
1.1.8 Device
The Device action allows you to view the books in the main memory or storage cards of your device, or to
eject the device (detach it from calibre). This icon shows up automatically on the main calibre toolbar when you connect
a supported device. You can click on it to see the books on your device. You can also drag and drop books from your
calibre library onto the icon to transfer them to your device. Conversely, you can drag and drop books from your device
onto the library icon on the toolbar to transfer books from your device to the calibre library.
8 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
1.1.9 Save to disk
The Save to disk action has ve variations, accessed by doing a right-click on the button.
1. Save to disk: Saves the selected books to disk organized in folders. The folder structure looks like:
Author_(sort)
Title
Book Files
You can control the le name and folder structure of les saved to disk by setting up a template in Prefer-
ences → Import/export → Saving books to disk. Also see The calibre template language (page 161).
2. Save to disk in a single folder: Saves the selected books to disk in a single folder.
For 1. and 2., all available formats, as well as metadata, are stored to disk for each selected book. Metadata
is stored in an OPF le. Saved books can be re-imported to the library without any loss of information by
using the Add books (page 4) action.
3. Save only *<your preferred>* format to disk: Saves the selected books to disk in the folder structure
as shown in (1.) but only in your preferred e-book format. You can set your preferred format in
Preferences → Interface → Behaviour → Preferred output format
4. Save only *<your preferred>* format to disk in a single folder: Saves the selected books to disk
in a single folder but only in your preferred e-book format. You can set your preferred format in
Preferences → Interface → Behaviour → Preferred output format
5. Save single format to disk…: Saves the selected books to disk in the folder structure as shown in (1.)
but only in the format you select from the popup list.
1.1.10 Connect/share
The Connect/share action allows you to manually connect to a device or folder on your computer.
It also allows you to set up your calibre library for access via a web browser or email.
The Connect/share action has four variations, accessed by doing a right-click on the button.
1. Connect to folder: Allows you to connect to any folder on your computer as though it were a device and
use all the facilities calibre has for devices with that folder. Useful if your device cannot be supported
by calibre but is available as a USB disk.
2. Start Content server: Starts calibre’s built-in web server. When started, your calibre library will be
accessible via a web browser from the Internet (if you choose). You can congure how the web server
is accessed by setting preferences at Preferences → Sharing → Sharing over the net
3. Setup email based sharing of books: Allows sharing of books and news feeds by email. After
setting up email addresses for this option, calibre will send news updates and book updates to the
1.1. Actions 9
calibre User Manual, Release 7.19.0
entered email addresses. You can congure how calibre sends email by setting preferences at Prefer-
ences → Sharing → Sharing books by email. Once you have set up one or more email addresses, this
menu entry will be replaced by menu entries to send books to the congured email addresses.
1.1.11 Remove books
The Remove books action deletes books permanently, so use it with care. It is context sensitive,
i.e. it depends on which catalog (page 11) you have selected. If you have selected the Library, books will be removed
from the library. If you have selected the e-book reader device, books will be removed from the device. To remove only
a particular format for a given book use the Edit metadata (page 5) action. Remove books also has ve variations which
can be accessed by doing a right-click on the button.
1. Remove selected books: Allows you to permanently remove all books that are selected in the book list.
2. Remove les of a specic format from selected books…: Allows you to permanently remove e-book les of a
specied format from books that are selected in the book list.
3. Remove all formats from selected books, except…
: Allows you to
permanently
remove e-book les of any
format except a specied format from books that are selected in the book list.
4. Remove all formats from selected books: Allows you to permanently remove all e-book les from books that
are selected in the book list. Only the metadata will remain.
5. Remove covers from selected books: Allows you to permanently remove cover image les from books that are
selected in the book list.
6. Remove matching books from device: Allows you to remove e-book les from a connected device that match
the books that are selected in the book list.
7. Restore recently deleted: Allows you to undo the removal of books or formats.
® Note
Note that when you use Remove books to delete books from your calibre library, the book record is deleted, but the
books are temporarily stored, for a few days, in a trash folder. You can undo the delete by right clicking the Remove
books button and choosing to Restore recently deleted books.
1.2 Preferences
The Preferences action allows you to change the way various aspects of calibre work. It has four
variations, accessed by doing a right-click on the button.
10 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
1. Preferences: Allows you to change the way various aspects of calibre work. Clicking the button also performs this
action.
2. Run Welcome wizard: Allows you to start the Welcome wizard which appeared the rst time you started calibre.
3. Get plugins to enhance calibre: Opens a new window that shows plugins for calibre. These plugins are developed
by third parties to extend calibre’s functionality.
4. Restart in debug mode: Allows you to enable a debugging mode that can assist the calibre developers in solving
problems you encounter with the program. For most users this should remain disabled unless instructed by a
developer to enable it.
1.3 Catalogs
A catalog is a collection of books. calibre can manage two types of dierent catalogs:
1. Library: This is a collection of books stored in your calibre library on your computer.
2. Device: This is a collection of books stored in your e-book reader. It will be available when you connect the reader
to your computer.
Many operations, such as adding books, deleting, viewing, etc., are context sensitive. So, for example, if you click the
View button when you have the Device catalog selected, calibre will open the les on the device to view. If you have the
Library catalog selected, les in your calibre library will be opened instead.
1.4 Search & sort
1.3. Catalogs 11
calibre User Manual, Release 7.19.0
The Search & Sort section allows you to perform several powerful actions on your book collections.
You can sort them by title, author, date, rating, etc. by clicking on the column titles. You can also sub-sort, i.e.
sort on multiple columns. For example, if you click on the title column and then the author column, the book will
be sorted by author and then all the entries for the same author will be sorted by title.
You can search for a particular book or set of books using the Search bar. More on that below.
You can quickly and conveniently edit metadata by selecting the entry you want changed in the list and pressing the
E key.
You can perform Actions (page 4) on sets of books. To select multiple books you can either:
Keep the Ctrl key pressed and click on the books you want selected.
Keep the Shift key pressed and click on the starting and ending book of a range of books you want selected.
You can congure which elds you want displayed by using the Preferences (page 10) dialog.
To perform complex multiple column based sub-sorting add the Sort by tool to a toolbar via Preferences → Toolbars
& menus.
1.5 The search interface
You can search all book metadata by entering search terms in the Search bar. For example:
Asimov Foundation format:lrf
This will match all books in your library that have Asimov and Foundation in their metadata and are available in the
LRF format. Some more examples:
author:Asimov and not series:Foundation
title:"The Ring" or "This book is about a ring"
format:epub publisher:feedbooks.com
Search kinds
There are four search kinds: contains, equality, regular expression (see regular expressions
2
), and character variant. You
choose the search kind with a prex character.
‘Contains’ searches
Searches with no prex character are contains and are by default case insensitive. An item matches if the search string
appears anywhere in the indicated metadata. You can make contains searches case sensitive by checking the option
Case sensitive searching in Preferences / Searching. If the search option Unaccented characters match accented characters
and punctuation is ignored
is checked then a character will match all its variants (e.g.,
e
matches
é
,
è
,
ê
, and
ë
) and all
punctuation and whitespace are ignored. For example, if the Unaccented characters match option is checked then given
the two book titles:
1. Big, Bothéred, and Bad
2. Big Bummer
then these searches nd:
title:"er" matches both (‘e’ matches both ‘é’ and ‘e’).
title:"g " matches both because spaces are ignored.
title:"g," matches both because the comma is ignored.
2
https://en.wikipedia.org/wiki/Regular_expression
12 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
title:"gb" matches both because ‘, is ignored in book 1 and spaces are ignored in book 2.
title:"g b" matches both because comma and space are ignored.
title:"db" matches #1 because the space in ‘and Bad’ is ignored.
title:"," matches both (it actually matches all books) because commas are ignored.
If the Unaccented characters match option is not checked then character variants, punctuation, and spacing are all
signicant.
You can set only one of the search options Case sensitive searching and Unaccented characters match accented characters
and punctuation is ignored.
‘Equality’ searches
Equality searches are indicated by prexing the search string with an equals sign (=). For example, the query
tag:"=science" will match science, but not science ction or hard science. Character variants are signicant: é
doesn’t match e.
Two variants of equality searches are used for hierarchical items (e.g., A.B.C): hierarchical prex searches and hierarchical
component searches. The rst, indicated by a single period after the equals (=.) matches the initial parts of a hierarchical
item. The second, indicated by two periods after the equals (=..) matches an internal name in the hierarchical item.
Examples, using the tag History.Military.WWII as the value:
tags:"=.History" : True. History is a prex of the tag.
tags:"=.History.Military" : True. History.Military is a prex of the tag.
tags:"=.History.Military.WWII" : True. History.Military.WWII is a prex of the tag, albeit
an improper one.
tags:"=.Military" : False. Military is not a prex of the tag.
tags:"=.WWII" : False. WWII is not a prex of the tag.
tags:"=..History" : True. The hierarchy contains the value History.
tags:"=..Military" : True. The hierarchy contains the value Military.
tags:"=..WWII" : True. The hierarchy contains the value WWII.
tags:"=..Military.WWII" : False. The .. search looks for single values.
‘Regular expression’ searches
Regular expression searches are indicated by prexing the search string with a tilde (~). Any Python-compatible regular
expression
3
can be used. Backslashes used to escape special characters in regular expressions must be doubled because
single backslashes will be removed during query parsing. For example, to match a literal parenthesis you must enter \\(
or alternatively use super-quotes (see below). Regular expression searches are ‘contains’ searches unless the expression is
anchored. Character variants are signicant: ~e doesn’t match é.
‘Character variant’ searches
Character variant searches are indicated by prexing the search string with a caret (^). This search is similar to the contains
search (above) except that:
letter case is always ignored.
character variants always match each other.
punctuation and whitespace are always signicant.
3
https://docs.python.org/library/re.html
1.5. The search interface 13
calibre User Manual, Release 7.19.0
The search options Unaccented characters match accented characters and punctuation is ignored and Case sensitive search-
ing are ignored. They have no eect on this search’s behavior.
The following compares this search to a contains search assuming the Unaccented characters match… option is checked
(see above) given the same two book titles:
1. Big, Bothéred, and Bad
2. Big Bummer
then these character variant searches nd:
title:"^er" matches both (‘e’ matches both ‘é’ and ‘e’)
title:"^g" matches both
title:"^g " matches #2 because the space is signicant
title:"^g," matches #1 because the comma is signicant
title:"^gb" matches nothing because space and comma are signicant
title:"^g b"
matches #2 because the comma is signicant
title:"^db" matches nothing
title:"^," matches #1 (instead of all books) because the comma is signicant
Search Expression Syntax
A search expression is a sequence of search terms optionally separated by the operators and and or. If two search terms
occur without a separating operator, and is assumed. The and operator has priority over the or operator; for example
the expression a or b and c is the same as a or (b and c). You can use parenthesis to change the priority; for
example (a or b) and c to make the or evaluate before the and. You can use the operator not to negate (invert)
the result of evaluating a search expression. Examples:
not tag:foo nds all books that don’t contain the tag foo
not (author:Asimov or author:Weber) nds all books not written by either Asimov or Weber.
The above examples show examples of search terms. A basic search term is a sequence of characters not including spaces,
quotes ("), backslashes (\), or parentheses (( )). It can be optionally preceded by a column name specier: the lookup
name of a column followed by a colon (:), for example author:Asimov. If a search term must contain a space then
the entire term must be enclosed in quotes, as in title:"The Ring". If the search term must contain quotes then
they must be escaped with backslashes. For example, to search for a series named The “Ball” and The “Chain”, use:
series:"The \"Ball\" and The \"Chain\"
If you need an actual backslash, something that happens frequently in regular expression searches, use two of them (\\).
It is sometimes hard to get all the escapes right so the result is what you want, especially in regular expression and template
searches. In these cases use the super-quote: """sequence of characters""". Super-quoted characters are
used unchanged: no escape processing is done.
More information
To search for a string that begins with an equals, tilde, or caret; prex the string with a backslash.
Enclose search strings with quotes (”) if the string contains parenthesis or spaces. For example, to nd books with the
tag Science Fiction you must search for tag:"=science fiction". If you search for tag:=science
fiction you will nd all books with the tag science and the word fiction in any metadata.
You can build advanced search queries easily using the Advanced search dialog accessed by clicking the button
on the left of the search box.
14 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
Available elds for searching are: tag, title, author, publisher, series, series_index,
rating, cover, comments, format, identifiers, date, pubdate, search, size, vl and
custom columns. If a device is plugged in, the ondevice eld becomes available, when searching the calibre library
view. To nd the search name (actually called the lookup name) for a custom column, hover your mouse over the column
header in the library view.
Dates
The syntax for searching for dates is:
pubdate:>2000-1 Will find all books published after Jan, 2000
date:<=2000-1-3 Will find all books added to calibre before 3 Jan, 2000
pubdate:=2009 Will find all books published in 2009
If the date is ambiguous then the current locale is used for date comparison. For example, in an mm/dd/yyyy locale
2/1/2009 is interpreted as 1 Feb 2009. In a dd/mm/yyyy locale it is interpreted as 2 Jan 2009. Some special date strings
are available. The string today translates to today’s date, whatever it is. The strings yesterday and thismonth
(or the translated equivalent in the current language) also work. In addition, the string daysago (also translated) can be
used to compare to a date some number of days ago. For example:
date:>10daysago
date:<=45daysago
To avoid potential problems with translated strings when using a non-English version of calibre, the strings _today,
_yesterday, _thismonth, and _daysago are always available. They are not translated.
Searching dates and numeric values with relational comparisons
Dates and numeric elds support the relational operators = (equals), > (greater than), >= (greater than or equal to), <
(less than), <= (less than or equal to), and != (not equal to). Rating elds are considered to be numeric. For example,
the search rating:>=3 will nd all books rated 3 or higher.
You can search for books that have a format of a certain size like this:
size:>1.1M will nd books with a format larger than 1.1MB
size:<=1K will nd books with a format smaller than or equal to 1KB
You can search for the number of items in multiple-valued elds such as tags using the character # then using the same
syntax as numeric elds. For example, to nd all books with more than 4 tags use tags:#>4. To nd all books with
exactly 10 tags use tags:#=10.
Series indices
Series indices are searchable. For the standard series, the search name is series_index. For custom series columns,
use the column search name followed by _index. For example, to search the indices for a custom series column named
#my_series, you would use the search name #my_series_index. Series indices are numbers, so you can use the
relational operators described above.
Saved searches
The special eld search is used for saved searches (page 18). If you save a search with the name “My spouse’s books”
you can enter search:"My spouse's books" in the Search bar to reuse the saved search. More about saving
searches below.
Virtual libraries
The special eld vl is used to search for books in a Virtual library. For example, vl:Read will nd all the books in
the Read Virtual library. The search vl:Read and vl:"Science Fiction" will nd all the books that are in
both the Read and Science Fiction virtual libraries. The value following vl: must be the name of a Virtual library. If the
Virtual library name contains spaces then surround it with quotes.
1.5. The search interface 15
calibre User Manual, Release 7.19.0
Whether a eld has a value
You can search for the absence or presence of a value for a eld using “true” and “false”. For example:
cover:false nds all books without a cover
series:true nds all books that are in a series
series:false nds all books that are not in a series
comments:false nds all books with an empty comment
formats:false nds all books with no book les (empty records)
Yes/no custom columns
Searching Yes/no custom columns for false, empty, or blank will nd all books with undened values in the column.
Searching for true will nd all books that do not have undened values in the column. Searching for yes or checked
will nd all books with Yes in the column. Searching for no or unchecked will nd all books with No in the column.
Note that the words yes, no, blank, empty, checked and unchecked are translated; you can use either the current
language’s equivalent word or the English word. The words true and false and the special values _yes, _no, and
_empty
are not translated.
Identiers
Identiers (e.g., ISBN, DOI, LCCN, etc.) use an extended syntax. An identier has the form type:value, as in
isbn:123456789. The extended syntax permits you to specify independently the type and value to search for. Both
the type and the value parts of the query can use any of the search kinds (page 12). Examples:
identifiers:true will nd books with any identier.
identifiers:false will nd books with no identier.
identifiers:123 will search for books with any type having a value containing 123.
identifiers:=123456789 will search for books with any type having a value equal to 123456789.
identifiers:=isbn: and identifiers:isbn:true will nd books with a type equal to ISBN having
any value
identifiers:=isbn:false will nd books with no type equal to ISBN.
identifiers:=isbn:123 will nd books with a type equal to ISBN having a value containing 123.
identifiers:=isbn:=123456789 will nd books with a type equal to ISBN having a value equal to
123456789.
identifiers:i:1 will nd books with a type containing an i having a value containing a 1.
Categories visible in the Tag browser
The search in_tag_browser:true nds all books that are in categories (tags, authors, etc.) currently shown in
the Tag browser. This is useful if you set the two preferences Preferences → Look & feel → Tag browser → Hide empty
categories and Find shows all items that match. With those two preferences set, doing a Find in the Tag browser shows only
categories containing items matched by the Find. Then, the search in_tag_browser:true additionally nds books
with these categories / items. You can easily run this search by pressing the key Ctrl+Alt+Shift+F or clicking the
congure button in the Tag browser and choosing the Show only books that have visible categories entry.
Search using templates
You can search using a template in The calibre template language (page 161) instead of a metadata eld. To do so you
enter a template, a search type, and the value to search for. The syntax is:
template: (the template) #@#: (search type) : (the value)
16 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
The template is any valid calibre template language template. The search type must be one of t (text search), d
(date search), n (numeric search), or b (set/not set (boolean)). The value is whatever you want, and can use the search
kinds (page 12) described above for the various search types. You must quote the entire search string if there are spaces
anywhere in it.
Examples:
template:"program: connected_device_name('main')#@#:t:kindle" is true when the
kindle device is connected.
template:"program: select(formats_sizes(), 'EPUB')#@#:n:>1000000" nds books
with EPUB les larger than 1 MB.
template:"program: select(formats_modtimes('iso'),
'EPUB')#@#:d:>10daysago" nds books with EPUB les newer than 10 days ago.
template:"""program: book_count('tags:^"' & $series & '"', 0) != 0#@#:n:1"""
nds all books containing the series name in the tags. This example uses super-quoting because the template uses
both single quotes (') and double quotes (") when constructing the search expression.
You can build template search queries easily using the Advanced search dialog accessed by clicking the button .
You can test templates on specic books using the calibre Template tester, which can be added to the toolbars or menus
via Preferences → Toolbars & menus. It can also be assigned a keyboard shortcut via Preferences → Shortcuts.
Advanced search dialog
Fig. 1: Advanced search dialog
1.5. The search interface 17
calibre User Manual, Release 7.19.0
1.6 Saving searches
calibre allows you to save a frequently used search under a special name and then reuse that search with a single click. To
do this, create your search either by typing it in the Search bar or using the Tag browser. Then type the name you would
like to give to the search in the Saved Searches box next to the Search bar. Click the plus icon next to the saved searches
box to save the search.
Now you can access your saved search in the Tag browser under Saved searches. A single click will allow you to reuse
any arbitrarily complex search easily, without needing to re-create it.
1.7 Searching the full text of all books
calibre can optionally index the full
text of books in the library to allow for instant searching of words inside any book. To use this functionality click the FT
button at the left edge of the search bar.
Then, enable indexing for the current library. Once indexing is complete you can search all the text in the full library.
When you add new books to the library, they will be automatically indexed in the background. This search allows you to
quickly nd all books that contain a word or combination of words. You can even search for words that occur near other
words, as shown in the examples in the search popup window. Note that this search tool will nd only one occurrence
of the search query in a particular book, not list every occurrence, for that it is best to search inside the book using the
calibre E-book viewer.
You can re-index an individual book by right clicking on the Book details panel in calibre and choosing Re-index this book
for full text searching.
18 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
1.8 Virtual libraries
A Virtual library is a way to pretend that your calibre library has only a few books instead of its full collection. This is
an excellent way to partition your large collection of books into smaller, manageable chunks. To learn how to create and
use Virtual libraries, see the tutorial: Virtual libraries (page 249).
1.9 Temporarily marking books
You can temporarily mark arbitrary sets of books. Marked books will have a pin on them and can be found with the
search marked:true. To mark a book press Ctrl+M or go to Preferences → Toolbars & menus and add the Mark
books button to the main toolbar.
You can mark books with a specic text label by right clicking the Mark books button and choosing Mark books with text
label. Books marked with text labels can later be found using the search marked:"=the-text-you-entered".
1.10 Guessing metadata from le names
Normally, calibre reads metadata from inside the book le. However, it can be congured to read metadata from the le
name instead, via Preferences → Import/export → Adding books → Read metadata from le contents.
You can also control how metadata is read from the lename using regular expressions (see All about using regular expres-
sions in calibre (page 215)). In the Adding books section of the conguration dialog, you can specify a regular expression
that calibre will use to try and guess metadata from the names of e-book les that you add to the library. The default
regular expression is:
title - author
that is, it assumes that all characters up to the rst - are the title of the book and subsequent characters are the author of
the book. For example, the lename:
Foundation and Earth - Isaac Asimov.txt
will be interpreted to have the title: Foundation and Earth and author: Isaac Asimov
b Tip
If the lename does not contain the hyphen, the above regular expression will fail.
1.8. Virtual libraries 19
calibre User Manual, Release 7.19.0
1.11 Book details
The Book details display shows the cover and all the metadata for the currently selected book. It can be hidden via the
20 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
Layout button in the lower right corner of the main calibre window. The author names shown in the Book details panel
are click-able, they will by default take you to the Wikipedia page for the author. This can be customized by right clicking
on the author name and selecting Manage this author.
Similarly, if you download metadata for the book, the Book details panel will automatically show you links pointing to
the web pages for the book on Amazon, WorldCat, etc. from where the metadata was downloaded.
You can right click on individual e-book formats in the Book details panel to delete them, compare them to their original
versions, save them to disk, open them with an external program, etc.
You can change the cover of the book by simply drag and dropping an image onto the Book details panel. If you wish to
edit the cover image in an external program, simply right click on it and choose Open with.
You can also add e-book les to the current book by drag and dropping the les onto the Book details panel.
Double clicking the Book details panel will open it up in a separate popup window.
Finally, you can customize exactly what information is displayed in the Book details panel via Prefer-
ences → Interface → Look & feel → Book details.
1.11. Book details 21
calibre User Manual, Release 7.19.0
1.12 Tag browser
The Tag browser allows you to easily browse your collection by Author/Tags/Series/etc. If you click on any item in the
Tag browser, for example the author name Isaac Asimov, then the list of books to the right is restricted to showing books
by that author. You can click on category names as well. For example, clicking on “Series” will show you all books in
any series.
The rst click on an item will restrict the list of books to those that contain or match the item. Continuing the above
example, clicking on Isaac Asimov will show books by that author. Clicking again on the item will change what is shown,
depending on whether the item has children (see sub-categories and hierarchical items below). Continuing the Isaac
Asimov example, clicking again on Isaac Asimov will restrict the list of books to those not by Isaac Asimov. A third
click will remove the restriction, showing all books. If you hold down the Ctrl or Shift keys and click on multiple
items, then restrictions based on multiple items are created. For example you could hold Ctrl and click on the tags
History and Europe for nding books on European history. The Tag browser works by constructing search expressions
that are automatically entered into the Search bar. Looking at what the Tag browser generates is a good way to learn how
to construct basic search expressions.
Items in the Tag browser have their icons partially colored. The amount of color depends on the average rating of the
22 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
books in that category. So for example if the books by Isaac Asimov have an average of four stars, the icon for Isaac
Asimov in the Tag browser will be 4/5th colored. You can hover your mouse over the icon to see the average rating.
The outer-level items in the Tag browser, such as Authors and Series, are called categories. You can create your own
categories, called User categories, which are useful for organizing items. For example, you can use the User categories
editor (click the Congure button at the lower-left of the Tag browser and choose Manage authors, tags, etc → User cate-
gories) to create a User category called Favorite Authors, then put the items for your favorites into the category.
User categories can have sub-categories. For example, the User category Favorites.Authors is a sub-category
of Favorites. You might also have Favorites.Series, in which case there will be two sub-categories under
Favorites. Sub-categories can be created by right-clicking on a User category, choosing Add sub-category to…, and
entering the sub-category name; or by using the User categories editor by entering names like the Favorites example above.
You can search User categories in the same way as built-in categories, by clicking on them. There are four
dierent searches cycled through by clicking:
1. “everything matching an item in the category” indicated by a single green plus sign.
2. “everything matching an item in the category or its sub-categories” indicated by two green plus signs.
3. “everything not matching an item in the category” shown by a single red minus sign.
4. “everything not matching an item in the category or its sub-categories” shown by two red minus signs.
It is also possible to create hierarchies inside some of the text categories such as tags, series, and custom columns. These
hierarchies show with the small triangle, permitting the sub-items to be hidden. To use hierarchies of items in a category,
you must rst go to Preferences → Interface → Look & feel and enter the category name(s) into the “Categories with
hierarchical items” eld. Once this is done, items in that category that contain periods will be shown using the small
triangle. For example, assume you create a custom column called “Genre” and indicate that it contains hierarchical items.
Once done, items such as Mystery.Thriller and Mystery.English will display as Mystery with the small triangle next to
it. Clicking on the triangle will show Thriller and English as sub-items. See Managing subgroups of books, for example
“genre” (page 153) for more information.
Hierarchical items (items with children) use the same four ‘click-on’ searches as User categories. Items that do not have
children use two of the searches: “everything matching” and “everything not matching”.
You can drag and drop items in the Tag browser onto User categories to add them to that category. If the source is a User
category, holding the Shift key while dragging will move the item to the new category. You can also drag and drop
books from the book list onto items in the Tag browser; dropping a book on an item causes that item to be automatically
applied to the dropped books. For example, dragging a book onto Isaac Asimov will set the author of that book to Isaac
Asimov. Dropping it onto the tag History will add the tag History to the book’s tags.
You can easily nd any item in the Tag browser by clicking the search button at the lower-right corner. In addition, you
can right click on any item and choose one of several operations. Some examples are to hide it, rename it, or open a
“Manage x” dialog that allows you to manage items of that kind. For example, the Manage authors dialog allows you to
rename authors and control how their names are sorted.
You can control how items are sorted in the Tag browser via the Congure button at the lower-left of the Tag browser.
You can choose to sort by name, average rating or popularity (popularity is the number of books with an item in your
library; for example, the popularity of Isaac Asimov is the number of books in your library by Isaac Asimov).
1.12. Tag browser 23
calibre User Manual, Release 7.19.0
1.13 Cover grid
You can have calibre display a grid of book covers instead of a list of books, if you prefer to browse your collection by
covers instead. The Cover grid is activated by clicking the Layout button in the bottom right corner of the main calibre
window. You can customize the cover sizes and the background of the Cover grid via Preferences → Interface → Look &
feel → Cover grid. You can even have calibre display any specied eld under the covers, such as title or authors or rating
or a custom column of your own devising.
24 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
1.14 Cover browser
In addition to the Cover grid described above, you can also have calibre display covers in the single row. This is activated
via the Layout button in the lower right corner of the main window. In Preferences → Interface → Look & feel → Cover
browser you can change the number of covers displayed, and even have the Cover browser display itself in a separate
popup window.
1.14. Cover browser 25
calibre User Manual, Release 7.19.0
1.15 Adding notes for authors, series, etc.
You can add notes for an author/series/tag/publisher/etc. to your calibre library. To do so right click on the author name
in the Tag browser on the left or the Book details panel on the right and choose Create note or Edit note.
A simple popup window will allow you to enter your notes using basic formatting and supporting links and images. Once
a note for an author is created, it can be viewed easily from the Book details panel by clicking the little pencil icon next to
the author name.
You can search through all the notes in your library using the Browse notes tool by pressing Ctrl+Shift+N or adding
it to the toolbar via Preferences → Toolbars & menus.
26 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
1.16 Quickview
Sometimes you want to select a book and quickly get a list of books with the same value in some category (authors, tags,
publisher, series, etc.) as the currently selected book, but without changing the current view of the library. You can do this
with Quickview. Quickview opens either a second window or a panel in the book list showing the list of books matching
the value of interest. For example, assume you want to see a list of all the books with the one or more of the authors of
the currently-selected book. Click in the author cell you are interested in and press the ‘Q’ key or click the Quickview icon
in the Layout section of the calibre window. A window or panel will open with all the authors for that book on the left,
and all the books by the selected author on the right.
Some example Quickview usages: quickly seeing what other books:
have some tag(s) applied to the currently selected book,
are in the same series as the current book
have the same values in a custom column as the current book
are written by one of the same authors of the current book
share values in a custom column
There are two choices for where the Quickview information appears:
1. It can open “undocked”: on top of the calibre window and will stay open until you explicitly close it.
2. It can open “docked”: as a panel in the book list section of the calibre main window.
You can move the window from docked to undocked as desired using the “Dock/Undock” button.
The Quickview panel can be left open permanently, in which case it follows movements on the book list. For example, if
you click in the calibre library view on a category column (tags, series, publisher, authors, etc.) for a book, the Quickview
window contents will change to show you in the left-hand side panel the values in that category for the selected book (e.g.,
the tags for that book). The rst item in that list will be selected, and Quickview will show you on the right-hand side
panel all the books in your library that use that value. Click on an dierent value in the left-hand panel to see the books
with that dierent value.
Double-click on a book in the Quickview window to select that book in the library view. This will also change the items
display in the QuickView window (the left-hand panel) to show the items in the newly-selected book.
Shift- or Ctrl- double-click on a book in the Quickview window to open the edit metadata dialog on that book in
the calibre window. The edited book will be Quickview’ed when you close the edit metadata dialog.
You can see if a column can be Quickview’ed by hovering your mouse over the column heading and looking at the tooltip
for that heading. You can also know by right-clicking on the column heading to see of the “Quickview” option is shown
in the menu, in which case choosing that Quickview option is equivalent to pressing ‘Q’ in the current cell.
Options (in Preferences → Look & feel → Quickview):
Respect (or not) the current Virtual library. If checked then Quickview shows only books in the current Virtual
library. Default: respect Virtual libraries
Change the Quickview window contents when the column is changed on the book list using the cursor keys. Default:
don’t follow changes made with cursor keys
Change the column being “quickview’ed” when a cell in the Quickview window is double-clicked. Otherwise the
book is changed but the column being examined is not. Default: change the column
Change the column being “quickview’ed” to the current column when the return key is pressed in the Quickview
panel. Otherwise the book is changed but the column being examined is not. Default: change the column
Choose which columns are shown in the Quickview window/panel.
1.16. Quickview 27
calibre User Manual, Release 7.19.0
1.17 Jobs
The Jobs panel shows the number of currently running jobs. Jobs are tasks that run in a separate process. They include
converting e-books and talking to your reader device. You can click on the jobs panel to access the list of jobs. Once a
job has completed you can see a detailed log from that job by double-clicking it in the list. This is useful to debug jobs
that may not have completed successfully.
1.18 Keyboard shortcuts
calibre has several keyboard shortcuts to save you time and mouse movement. These shortcuts are active in the book list
view (when you’re not editing the details of a particular book), and most of them aect the title you have selected. The
calibre E-book viewer has its own shortcuts (page 55) which can be customised in the viewer Preferences.
® Note
Note: The calibre keyboard shortcuts do not require a modier key (Command, Option, Control, etc.), unless specif-
ically noted. You only need to press the letter key, e.g. E to edit.
Table 1: Keyboard shortcuts for the main calibre program
Key-
board
short-
cut
Action
F2
(En-
ter
for
ma-
cOS)
Edit the metadata of the currently selected eld in the book list.
A Add books
Shift+AAdd formats to the selected books
C Convert selected books
D Send to device
Del Remove selected books
E Edit metadata of selected books
G Get books
I Show Book details
K Edit Table of Contents
M Merge selected records
Alt+M Merge selected records, keeping originals
O Open containing folder
P Polish books
S Save to disk
T Edit book
continues on next page
28 Chapter 1. The Graphical User Interface
calibre User Manual, Release 7.19.0
Table 1 continued from previous page
Key-
board
short-
cut
Action
V View
Shift+VView last read book
Alt+V/
Cmd+V
for
macOS
View specic format
Alt+Shift+JToggle jobs list
Alt+Shift+BToggle Cover browser
Alt+Shift+DToggle Book details panel
Alt+Shift+TToggle Tag browser
Alt+Shift+GToggle Cover grid
Alt+A Show books by the same author as the current book
Alt+T Show books with the same tags as current book
Alt+P Show books by the same publisher as current book
Alt+Shift+SShow books in the same series as current book
/,
Ctrl+F
Focus the Search bar
Shift+Ctrl+FOpen the Advanced search dialog
Shift+Alt+FToggle the Search bar
Esc Clear the current search
Shift+EscFocus the book list
Ctrl+EscClear the Virtual library
Alt+EscClear the additional restriction
Ctrl+* Create a temporary Virtual library based on the current search
Ctrl+RightSelect the next Virtual library tab
Ctrl+LeftSelect the previous Virtual library tab
N or
F3
Find the next book that matches the current search (only works if search highlighting is turned on in search
preferences)
Shift+N
or
Shift+F3
Find the previous book that matches the current search (only works if search highlighting is turned on in
search preferences)
Ctrl+D Download metadata and covers
Ctrl+R Restart calibre
Ctrl+Shift+RRestart calibre in debug mode
Shift+Ctrl+EAdd empty books to calibre
Ctrl+M Toggle mark/unmarked status on selected books
Ctrl+/
or
Ctrl+Alt+F
Open the popup to search the full text of all books in the library
Q Open the Quick View popup for viewing books in related series/tags/etc.
Shift+QFocus the opened Quick View panel
Shift+SPerform a search in the Quick View panel
F5 Re-apply the current sort
Ctrl+Q Quit calibre
X Toggle auto scroll of the book list
Ctrl+Alt+Shift+FRestrict the displayed books to only those books that are in a category currently displayed in the Tag browser
continues on next page
1.18. Keyboard shortcuts 29
calibre User Manual, Release 7.19.0
Table 1 continued from previous page
Key-
board
short-
cut
Action
B Browse annotations (highlights and bookmarks) made in the calibre E-book viewer for all books in the
library
Ctrl+Shift+NBrowse notes associated with authors/series/tags/etc.
Alt+Shift+LToggle the layout between wide and narrow views
30 Chapter 1. The Graphical User Interface
CHAPTER
TWO
ADDING YOUR FAVORITE NEWS WEBSITE
calibre has a powerful, exible and easy-to-use framework for downloading news from the Internet and converting it into
an e-book. The following will show you, by means of examples, how to get news from various websites.
To gain an understanding of how to use the framework, follow the examples in the order listed below:
Completely automatic fetching (page 32)
The calibre blog (page 32)
bbc.co.uk (page 33)
Customizing the fetch process (page 33)
Using the print version of bbc.co.uk (page 33)
Replacing article styles (page 35)
Slicing and dicing (page 35)
Real life example (page 36)
Tips for developing new recipes (page 38)
Further reading (page 39)
API documentation (page 39)
31
calibre User Manual, Release 7.19.0
2.1 Completely automatic fetching
If your news source is simple enough, calibre may well be able to fetch it completely automatically, all you need to do
is provide the URL. calibre gathers all the information needed to download a news source into a recipe. In order to tell
calibre about a news source, you have to create a recipe for it. Let’s see some examples:
2.1.1 The calibre blog
The calibre blog is a blog of posts that describe many useful calibre features in a simple and accessible way for new calibre
users. In order to download this blog into an e-book, we rely on the RSS feed of the blog:
http://blog.calibre-ebook.com/feeds/posts/default
I got the RSS URL by looking under “Subscribe to” at the bottom of the blog page and choosing Posts → Atom. To make
calibre download the feeds and convert them into an e-book, you should right click the Fetch news button and then the
Add a custom news source menu item and then the New Recipe button. A dialog similar to that shown below should open
up.
32 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
First enter Calibre Blog into the Recipe title eld. This will be the title of the e-book that will be created from the
articles in the above feeds.
The next two elds (Oldest article and Max. number of articles) allow you some control over how many articles should be
downloaded from each feed, and they are pretty self explanatory.
To add the feeds to the recipe, enter the feed title and the feed URL and click the Add feed button. Once you have added
the feed, simply click the Save button and you’re done! Close the dialog.
To test your new recipe, click the Fetch news button and in the Custom news sources sub-menu click calibre Blog. After
a couple of minutes, the newly downloaded e-book of blog posts will appear in the main library view (if you have your
reader connected, it will be put onto the reader instead of into the library). Select it and hit the View button to read!
The reason this worked so well, with so little eort is that the blog provides full-content RSS feeds, i.e., the article content
is embedded in the feed itself. For most news sources that provide news in this fashion, with full-content feeds, you don’t
need any more eort to convert them to e-books. Now we will look at a news source that does not provide full content
feeds. In such feeds, the full article is a webpage and the feed only contains a link to the webpage with a short summary
of the article.
2.1.2 bbc.co.uk
Let’s try the following two feeds from The BBC:
1. News Front Page: https://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml
2. Science/Nature: https://newsrss.bbc.co.uk/rss/newsonline_world_edition/science/nature/rss.xml
Follow the procedure outlined in The calibre blog (page 32) above to create a recipe for The BBC (using the feeds above).
Looking at the downloaded e-book, we see that calibre has done a creditable job of extracting only the content you care
about from each article’s webpage. However, the extraction process is not perfect. Sometimes it leaves in undesirable
content like menus and navigation aids or it removes content that should have been left alone, like article headings. In
order, to have perfect content extraction, we will need to customize the fetch process, as described in the next section.
2.2 Customizing the fetch process
When you want to perfect the download process, or download content from a particularly complex website, you can avail
yourself of all the power and exibility of the recipe framework. In order to do that, in the Add custom news sources
dialog, simply click the Switch to Advanced mode button.
The easiest and often most productive customization is to use the print version of the online articles. The print version
typically has much less cruft and translates much more smoothly to an e-book. Let’s try to use the print version of the
articles from The BBC.
2.2.1 Using the print version of bbc.co.uk
The rst step is to look at the e-book we downloaded previously from bbc.co.uk (page 33). At the end of each article, in
the e-book is a little blurb telling you where the article was downloaded from. Copy and paste that URL into a browser.
Now on the article webpage look for a link that points to the “Printable version”. Click it to see the print version of the
article. It looks much neater! Now compare the two URLs. For me they were:
Article URL
https://news.bbc.co.uk/2/hi/science/nature/7312016.stm
2.2. Customizing the fetch process 33
calibre User Manual, Release 7.19.0
Print version URL
https://newsvote.bbc.co.uk/mpapps/pagetools/print/news.bbc.co.uk/2/hi/science/nature/7312016.
stm
So it looks like to get the print version, we need to prex every article URL with:
newsvote.bbc.co.uk/mpapps/pagetools/print/
Now in the Advanced mode of the Custom news sources dialog, you should see something like (remember to select The
BBC recipe before switching to advanced mode):
You can see that the elds from the
Basic mode
have been translated to Python code in a straightforward manner. We
need to add instructions to this recipe to use the print version of the articles. All that’s needed is to add the following two
lines:
def print_version(self, url):
return url.replace('https://', 'https://newsvote.bbc.co.uk/mpapps/pagetools/print/
,')
This is Python, so indentation is important. After you’ve added the lines, it should look like:
In the above, def print_version(self, url) denes a method that is called by calibre for every article. url
is the URL of the original article. What print_version does is take that url and replace it with the new URL that
points to the print version of the article. To learn about Python
4
see the tutorial
5
.
Now, click the Add/update recipe button and your changes will be saved. Re-download the e-book. You should have a
much improved e-book. One of the problems with the new version is that the fonts on the print version webpage are too
small. This is automatically xed when converting to an e-book, but even after the xing process, the font size of the
4
https://www.python.org
5
https://docs.python.org/tutorial/
34 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
menus and navigation bar become too large relative to the article text. To x this, we will do some more customization,
in the next section.
2.2.2 Replacing article styles
In the previous section, we saw that the font size for articles from the print version of The BBC was too small. In most
websites, The BBC included, this font size is set by means of CSS stylesheets. We can disable the fetching of such
stylesheets by adding the line:
no_stylesheets = True
The recipe now looks like:
The new version looks pretty good. If you’re a perfectionist, you’ll want to read the next section, which deals with actually
modifying the downloaded content.
2.2.3 Slicing and dicing
calibre contains very powerful and exible abilities when it comes to manipulating downloaded content. To show o a
couple of these, let’s look at our old friend the The BBC (page 35) recipe again. Looking at the source code (HTML) of
a couple of articles (print version), we see that they have a footer that contains no useful information, contained in
<div class="footer">
...
</div>
This can be removed by adding:
remove_tags = [dict(name='div', attrs={'class':'footer'})]
to the recipe. Finally, lets replace some of the CSS that we disabled earlier, with our own CSS that is suitable for conversion
to an e-book:
extra_css = '.headline {font-size: x-large;} \n .fact { padding-top: 10pt }'
With these additions, our recipe has become “production quality”.
This recipe explores only the tip of the iceberg when it comes to the power of calibre. To explore more of the abilities of
calibre we’ll examine a more complex real life example in the next section.
2.2. Customizing the fetch process 35
calibre User Manual, Release 7.19.0
2.2.4 Real life example
A reasonably complex real life example that exposes more of the API of BasicNewsRecipe is the recipe for The New
York Times
import string, re
from calibre import strftime
from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import BeautifulSoup
class NYTimes(BasicNewsRecipe):
title = 'The New York Times'
__author__ = 'Kovid Goyal'
description = 'Daily news from the New York Times'
timefmt = ' [%a, %d %b, %Y]'
needs_subscription = True
remove_tags_before = dict(id='article')
remove_tags_after = dict(id='article')
remove_tags = [dict(attrs={'class':['articleTools', 'post-tools', 'side_tool',
,'nextArticleLink clearfix']}),
dict(id=['footer', 'toolsRight', 'articleInline', 'navigation',
,'archive', 'side_search', 'blog_sidebar', 'side_tool', 'side_index']),
dict(name=['script', 'noscript', 'style'])]
encoding = 'cp1252'
no_stylesheets = True
extra_css = 'h1 {font: sans-serif large;}\n.byline {font:monospace;}'
def get_browser(self):
br = BasicNewsRecipe.get_browser(self)
if self.username is not None and self.password is not None:
br.open('https://www.nytimes.com/auth/login')
br.select_form(name='login')
br['USERID'] = self.username
br['PASSWORD'] = self.password
br.submit()
return br
def parse_index(self):
soup = self.index_to_soup('https://www.nytimes.com/pages/todayspaper/index.
,html')
def feed_title(div):
return ''.join(div.findAll(text=True, recursive=False)).strip()
articles = {}
key = None
ans = []
for div in soup.findAll(True,
attrs={'class':['section-headline', 'story', 'story headline']}):
if ''.join(div['class']) == 'section-headline':
key = string.capwords(feed_title(div))
articles[key] = []
ans.append(key)
elif ''.join(div['class']) in ['story', 'story headline']:
a = div.find('a', href=True)
(continues on next page)
36 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
(continued from previous page)
if not a:
continue
url = re.sub(r'\?.*', '', a['href'])
url += '?pagewanted=all'
title = self.tag_to_string(a, use_alt=True).strip()
description = ''
pubdate = strftime('%a, %d %b')
summary = div.find(True, attrs={'class':'summary'})
if summary:
description = self.tag_to_string(summary, use_alt=False)
feed = key if key is not None else 'Uncategorized'
if feed not in articles:
articles[feed] = []
if not 'podcasts' in url:
articles[feed].append(
dict(title=title, url=url, date=pubdate,
description=description,
content=''))
ans = self.sort_index_by(ans, {'The Front Page':-1, 'Dining In, Dining Out':1,
, 'Obituaries':2})
ans = [(key, articles[key]) for key in ans if key in articles]
return ans
def preprocess_html(self, soup):
refresh = soup.find('meta', {'http-equiv':'refresh'})
if refresh is None:
return soup
content = refresh.get('content').partition('=')[2]
raw = self.browser.open('https://www.nytimes.com'+content).read()
return BeautifulSoup(raw.decode('cp1252', 'replace'))
We see several new features in this recipe. First, we have:
timefmt = ' [%a, %d %b, %Y]'
This sets the displayed time on the front page of the created e-book to be in the format, Day, Day_Number Month,
Year. See timefmt (page 49).
Then we see a group of directives to cleanup the downloaded HTML:
remove_tags_before = dict(name='h1')
remove_tags_after = dict(id='footer')
remove_tags = ...
These remove everything before the rst <h1> tag and everything after the rst tag whose id is footer. See re-
move_tags (page 48), remove_tags_before (page 48), remove_tags_after (page 48).
The next interesting feature is:
needs_subscription = True
...
def get_browser(self):
...
needs_subscription = True tells calibre that this recipe needs a username and password in order to access
the content. This causes, calibre to ask for a username and password whenever you try to use this recipe. The code in
calibre.web.feeds.news.BasicNewsRecipe.get_browser() (page 40) actually does the login into the
2.2. Customizing the fetch process 37
calibre User Manual, Release 7.19.0
NYT website. Once logged in, calibre will use the same, logged in, browser instance to fetch all content. See mechanize
6
to understand the code in get_browser.
The next new feature is the calibre.web.feeds.news.BasicNewsRecipe.parse_index() (page 42)
method. Its job is to go to https://www.nytimes.com/pages/todayspaper/index.html and fetch the list of articles that
appear in todays paper. While more complex than simply using RSS, the recipe creates an e-book that corresponds very
closely to the days paper. parse_index makes heavy use of BeautifulSoup
7
to parse the daily paper webpage. You
can also use other, more modern parsers if you dislike BeautifulSoup. calibre comes with lxml
8
and html5lib
9
, which are
the recommended parsers. To use them, replace the call to index_to_soup() with the following:
raw = self.index_to_soup(url, raw=True)
# For html5lib
import html5lib
root = html5lib.parse(raw, namespaceHTMLElements=False, treebuilder='lxml')
# For the lxml html 4 parser
from lxml import html
root = html.fromstring(raw)
The nal new feature is the calibre.web.feeds.news.BasicNewsRecipe.preprocess_html()
(page 43) method. It can be used to perform arbitrary transformations on every downloaded HTML page. Here it is
used to bypass the ads that the nytimes shows you before each article.
2.3 Tips for developing new recipes
The best way to develop new recipes is to use the command line interface. Create the recipe using your favorite Python
editor and save it to a le say myrecipe.recipe. The .recipe extension is required. You can download content using
this recipe with the command:
ebook-convert myrecipe.recipe .epub --test -vv --debug-pipeline debug
The command ebook-convert will download all the webpages and save them to the EPUB le myrecipe.
epub. The -vv option makes ebook-convert spit out a lot of information about what it is doing. The
ebook-convert-recipe-input --test (page 339) option makes it download only a couple of articles from
at most two feeds. In addition, ebook-convert will put the downloaded HTML into the debug/input folder, where
debug is the folder you specied in the ebook-convert --debug-pipeline (page 334) option.
Once the download is complete, you can look at the downloaded HTML by opening the le debug/input/index.
html in a browser. Once you’re satised that the download and preprocessing is happening correctly, you can generate
e-books in dierent formats as shown below:
ebook-convert myrecipe.recipe myrecipe.epub
ebook-convert myrecipe.recipe myrecipe.mobi
...
If you’re satised with your recipe, and you feel there is enough demand to justify its inclusion into the set of built-in
recipes, post your recipe in the calibre recipes forum
10
to share it with other calibre users.
6
https://mechanize.readthedocs.io/en/latest/
7
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
8
https://lxml.de/
9
https://github.com/html5lib/html5lib-python
10
https://www.mobileread.com/forums/forumdisplay.php?f=228
38 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
® Note
On macOS, the command line tools are inside the calibre bundle, for example, if you installed calibre in /
Applications the command line tools are in /Applications/calibre.app/Contents/MacOS/.
µ See also
ebook-convert (page 325)
The command line interface for all e-book conversion.
2.4 Further reading
To learn more about writing advanced recipes using some of the facilities, available in BasicNewsRecipe you should
consult the following sources:
API documentation (page 39)
Documentation of the BasicNewsRecipe class and all its important methods and elds.
BasicNewsRecipe
11
The source code of BasicNewsRecipe
Built-in recipes
12
The source code for the built-in recipes that come with calibre
The calibre recipes forum
13
Lots of knowledgeable calibre recipe writers hang out here.
2.5 API documentation
2.5.1 API documentation for recipes
The API for writing recipes is dened by the BasicNewsRecipe (page 39)
class calibre.web.feeds.news.BasicNewsRecipe(options, log, progress_reporter)
Base class that contains logic needed in all recipes. By overriding progressively more of the functionality in this
class, you can make progressively more customized/powerful recipes. For a tutorial introduction to creating recipes,
see Adding your favorite news website (page 31).
abort_article(msg=None)
Call this method inside any of the preprocess methods to abort the download for the current article. Useful
to skip articles that contain inappropriate content, such as pure video articles.
abort_recipe_processing(msg)
Causes the recipe download system to abort the download of this recipe, displaying a simple feedback message
to the user.
11
https://github.com/kovidgoyal/calibre/blob/master/src/calibre/web/feeds/news.py
12
https://github.com/kovidgoyal/calibre/tree/master/recipes
13
https://www.mobileread.com/forums/forumdisplay.php?f=228
2.4. Further reading 39
calibre User Manual, Release 7.19.0
add_toc_thumbnail(article, src)
Call this from populate_article_metadata with the src attribute of an <img> tag from the article that is appro-
priate for use as the thumbnail representing the article in the Table of Contents. Whether the thumbnail is
actually used is device dependent (currently only used by the Kindles). Note that the referenced image must
be one that was successfully downloaded, otherwise it will be ignored.
classmethod adeify_images(soup)
If your recipe when converted to EPUB has problems with images when viewed in Adobe Digital Editions,
call this method from within postprocess_html() (page 43).
canonicalize_internal_url(url, is_link=True)
Return a set of canonical representations of url. The default implementation uses just the server hostname
and path of the URL, ignoring any query parameters, fragments, etc. The canonical representations must be
unique across all URLs for this news source. If they are not, then internal links may be resolved incorrectly.
Parameters
is_link Is True if the URL is coming from an internal link in an HTML le. False if the
URL is the URL used to download an article.
cleanup()
Called after all articles have been download. Use it to do any cleanup like logging out of subscription sites,
etc.
clone_browser(br)
Clone the browser br. Cloned browsers are used for multi-threaded downloads, since mechanize is not thread
safe. The default cloning routines should capture most browser customization, but if you do something exotic
in your recipe, you should override this method in your recipe and clone manually.
Cloned browser instances use the same, thread-safe CookieJar by default, unless you have customized cookie
handling.
default_cover(cover_le)
Create a generic cover for recipes that don’t have a cover
download()
Download and pre-process all articles from the feeds in this recipe. This method should be called only once
on a particular Recipe instance. Calling it more than once will lead to undened behavior. :return: Path to
index.html
extract_readable_article(html, url)
Extracts main article content from ‘html’, cleans up and returns as a (article_html, extracted_title) tuple. Based
on the original readability algorithm by Arc90.
get_article_url(article)
Override in a subclass to customize extraction of the URL that points to the content for each article. Return
the article URL. It is called with article, an object representing a parsed article from a feed. See feedparser
14
.
By default it looks for the original link (for feeds syndicated via a service like FeedBurner or Pheedo) and if
found, returns that or else returns article.link
15
.
get_browser(*args, **kwargs)
Return a browser instance used to fetch documents from the web. By default it returns a mechanize
16
browser
instance that supports cookies, ignores robots.txt, handles refreshes and has a random common user agent.
To customize the browser override this method in your sub-class as:
40 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
def get_browser(self, *a, **kw):
br = super().get_browser(*a, **kw)
# Add some headers
br.addheaders += [
('My-Header', 'one'),
('My-Header2', 'two'),
]
# Set some cookies
br.set_cookie('name', 'value')
br.set_cookie('name2', 'value2', domain='.mydomain.com')
# Make a POST request with some data
br.open('https://someurl.com', {'username': 'def', 'password': 'pwd'}).
,read()
# Do a login via a simple web form (only supported with mechanize
,browsers)
if self.username is not None and self.password is not None:
br.open('https://www.nytimes.com/auth/login')
br.select_form(name='login')
br['USERID'] = self.username
br['PASSWORD'] = self.password
br.submit()
return br
get_cover_url()
Return a URL to the cover image for this issue or None. By default it returns the value of the member
self.cover_url which is normally None. If you want your recipe to download a cover for the e-book override
this method in your subclass, or set the member variable self.cover_url before this method is called.
get_extra_css()
By default returns self.extra_css. Override if you want to programmatically generate the extra_css.
get_feeds()
Return a list of RSS feeds to fetch for this prole. Each element of the list must be a 2-element tuple of the
form (title, url). If title is None or an empty string, the title from the feed is used. This method is useful if
your recipe needs to do some processing to gure out the list of feeds to download. If so, override in your
subclass.
get_masthead_title()
Override in subclass to use something other than the recipe title
get_masthead_url()
Return a URL to the masthead image for this issue or None. By default it returns the value of the member
self.masthead_url which is normally None. If you want your recipe to download a masthead for the e-book
override this method in your subclass, or set the member variable self.masthead_url before this method is
called. Masthead images are used in Kindle MOBI les.
get_obfuscated_article(url)
If you set articles_are_obfuscated this method is called with every article URL. It should return the path to a
le on the lesystem that contains the article HTML. That le is processed by the recursive HTML fetching
engine, so it can contain links to pages/images on the web. Alternately, you can return a dictionary of the form:
{‘data’: <HTML data>, ‘url’: <the resolved URL of the article>}. This avoids needing to create temporary
les. The url key in the dictionary is useful if the eective URL of the article is dierent from the URL
passed into this method, for example, because of redirects. It can be omitted if the URL is unchanged.
This method is typically useful for sites that try to make it dicult to access article content automatically.
2.5. API documentation 41
calibre User Manual, Release 7.19.0
get_url_specific_delay(url)
Return the delay in seconds before downloading this URL. If you want to programmatically determine the
delay for the specied URL, override this method in your subclass, returning self.delay by default for URLs
you do not want to aect.
Returns
A oating point number, the delay in seconds.
classmethod image_url_processor(baseurl, url)
Perform some processing on image urls (perhaps removing size restrictions for dynamically generated images,
etc.) and return the processed URL. Return None or an empty string to skip fetching the image.
index_to_soup(url_or_raw, raw=False, as_tree=False, save_raw=None)
Convenience method that takes an URL to the index page and returns a BeautifulSoup
17
of it.
url_or_raw: Either a URL or the downloaded index page as a string
is_link_wanted(url, tag)
Return True if the link should be followed or False otherwise. By default, raises NotImplementedError which
causes the downloader to ignore it.
Parameters
url The URL to be followed
tag The tag from which the URL was derived
parse_feeds()
Create a list of articles from the list of feeds returned by BasicNewsRecipe.get_feeds() (page 41).
Return a list of Feed objects.
parse_index()
This method should be implemented in recipes that parse a website instead of feeds to generate a list of
articles. Typical uses are for news sources that have a “Print Edition” webpage that lists all the articles in the
current print edition. If this function is implemented, it will be used in preference to BasicNewsRecipe.
parse_feeds() (page 42).
It must return a list. Each element of the list must be a 2-element tuple of the form ('feed title',
list of articles).
Each list of articles must contain dictionaries of the form:
{
'title' : article title,
'url' : URL of print version,
'date' : The publication date of the article as a string,
'description' : A summary of the article
'content' : The full article (can be an empty string). Obsolete
do not use, instead save the content to a temporary
file and pass a file:///path/to/temp/file.html as
the URL.
}
For an example, see the recipe for downloading The Atlantic. In addition, you can add ‘author’ for the author
of the article.
If you want to abort processing for some reason and have calibre show the user a simple message instead of
an error, call abort_recipe_processing() (page 39).
42 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
populate_article_metadata(article, soup, rst)
Called when each HTML page belonging to article is downloaded. Intended to be used to get article metadata
like author/summary/etc. from the parsed HTML (soup).
Parameters
article A object of class calibre.web.feeds.Article. If you change the
summary, remember to also change the text_summary
soup Parsed HTML belonging to this article
first True i the parsed HTML is the rst page of the article.
postprocess_book(oeb, opts, log)
Run any needed post processing on the parsed downloaded e-book.
Parameters
oeb An OEBBook object
opts Conversion options
postprocess_html(soup, rst_fetch)
This method is called with the source of each downloaded HTML le, after it is parsed for links and images.
It can be used to do arbitrarily powerful post-processing on the HTML. It should return soup after processing
it.
Parameters
soup A BeautifulSoup
18
instance containing the downloaded HTML.
first_fetch True if this is the rst page of an article.
preprocess_html(soup)
This method is called with the source of each downloaded HTML le, before it is parsed for links and images.
It is called after the cleanup as specied by remove_tags etc. It can be used to do arbitrarily powerful pre-
processing on the HTML. It should return soup after processing it.
soup: A BeautifulSoup
19
instance containing the downloaded HTML.
preprocess_image(img_data, image_url)
Perform some processing on downloaded image data. This is called on the raw data before any resizing is
done. Must return the processed raw data. Return None to skip the image.
preprocess_raw_html(raw_html, url)
This method is called with the source of each downloaded HTML le, before it is parsed into an object tree.
raw_html is a unicode string representing the raw HTML downloaded from the web. url is the URL from
which the HTML was downloaded.
Note that this method acts before preprocess_regexps.
This method must return the processed raw_html as a unicode object.
classmethod print_version(url)
Take a url pointing to the webpage with article content and return the URL pointing to the print version of
the article. By default does nothing. For example:
def print_version(self, url):
return url + '?&pagewanted=print'
2.5. API documentation 43
calibre User Manual, Release 7.19.0
publication_date()
Use this method to set the date when this issue was published. Defaults to the moment of download. Must
return a datetime.datetime object.
skip_ad_pages(soup)
This method is called with the source of each downloaded HTML le, before any of the cleanup attributes
like remove_tags, keep_only_tags are applied. Note that preprocess_regexps will have already been applied.
It is meant to allow the recipe to skip ad pages. If the soup represents an ad page, return the HTML of the
real page. Otherwise return None.
soup: A BeautifulSoup
20
instance containing the downloaded HTML.
sort_index_by(index, weights)
Convenience method to sort the titles in index according to weights. index is sorted in place. Returns index.
index: A list of titles.
weights: A dictionary that maps weights to titles. If any titles in index are not in weights, they are assumed to
have a weight of 0.
classmethod tag_to_string(tag, use_alt=True, normalize_whitespace=True)
Convenience method to take a BeautifulSoup
21
Tag and extract the text from it recursively, including any
CDATA sections and alt tag attributes. Return a possibly empty Unicode string.
use_alt: If True try to use the alt attribute for tags that don’t have any textual content
tag: BeautifulSoup
22
Tag
articles_are_obfuscated = False
Set to True and implement get_obfuscated_article() (page 41) to handle websites that try to make
it dicult to scrape content.
auto_cleanup = False
Automatically extract all the text from downloaded article pages. Uses the algorithms from the readability
project. Setting this to True, means that you do not have to worry about cleaning up the downloaded HTML
manually (though manual cleanup will always be superior).
auto_cleanup_keep = None
Specify elements that the auto cleanup algorithm should never remove. The syntax is a XPath expression. For
example:
auto_cleanup_keep = '//div[@id="article-image"]' will keep all divs with
id="article-image"
auto_cleanup_keep = '//*[@class="important"]' will keep all elements
with class="important"
auto_cleanup_keep = '//div[@id="article-image"]|//span[@class="important"]'
will keep all divs with id="article-image" and spans
with class="important"
browser_type = 'mechanize'
The simulated browser engine to use when downloading from servers. The default is to use the Python mech-
anize browser engine, which supports logging in. However, if you don’t need logging in, consider changing
this to either ‘webengine’ which uses an actual Chromium browser to do the network requests or ‘qt’ which
uses the Qt Networking backend. Both ‘webengine’ and ‘qt’ support HTTP/2, which mechanize does not and
are thus harder to ngerprint for bot protection services.
center_navbar = True
If True the navigation bar is center aligned, otherwise it is left aligned
44 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
compress_news_images = False
Set this to False to ignore all scaling and compression parameters and pass images through unmodied. If
True and the other compression parameters are left at their default values, JPEG images will be scaled to t
in the screen dimensions set by the output prole and compressed to size at most (w * h)/16 where w x h are
the scaled image dimensions.
compress_news_images_auto_size = 16
The factor used when auto compressing JPEG images. If set to None, auto compression is disabled. Oth-
erwise, the images will be reduced in size to (w * h)/compress_news_images_auto_size bytes if possible by
reducing the quality level, where w x h are the image dimensions in pixels. The minimum JPEG quality will
be 5/100 so it is possible this constraint will not be met. This parameter can be overridden by the parameter
compress_news_images_max_size which provides a xed maximum size for images. Note that if you enable
scale_news_images_to_device then the image will rst be scaled and then its quality lowered until its size is
less than (w * h)/factor where w and h are now the scaled image dimensions. In other words, this compression
happens after scaling.
compress_news_images_max_size = None
Set JPEG quality so images do not exceed the size given (in KBytes). If set, this parameter overrides auto
compression via compress_news_images_auto_size. The minimum JPEG quality will be 5/100 so it is pos-
sible this constraint will not be met.
conversion_options = {}
Recipe specic options to control the conversion of the downloaded content into an e-book. These will
override any user or plugin specied values, so only use if absolutely necessary. For example:
conversion_options = {
'base_font_size' : 16,
'linearize_tables' : True,
}
cover_margins = (0, 0, '#ffffff')
By default, the cover image returned by get_cover_url() will be used as the cover for the periodical. Overriding
this in your recipe instructs calibre to render the downloaded cover into a frame whose width and height are
expressed as a percentage of the downloaded cover. cover_margins = (10, 15, ‘#’) pads the cover with a
white margin 10px on the left and right, 15px on the top and bottom. Color names are dened here
23
. Note
that for some reason, white does not always work in Windows. Use # instead
delay = 0
The default delay between consecutive downloads in seconds. The argument may be a oating point number
to indicate a more precise time. See get_url_specific_delay() (page 41) to implement per URL
delays.
description = ''
A couple of lines that describe the content this recipe downloads. This will be used primarily in a GUI that
presents a list of recipes.
encoding = None
Specify an override encoding for sites that have an incorrect charset specication. The most common being
specifying latin1 and using cp1252. If None, try to detect the encoding. If it is a callable, the callable
is called with two arguments: The recipe object and the source to be decoded. It must return the decoded
source.
extra_css = None
Specify any extra CSS that should be added to downloaded HTML les. It will be inserted into <style> tags,
just before the closing </head> tag thereby overriding all CSS except that which is declared using the style
2.5. API documentation 45
calibre User Manual, Release 7.19.0
attribute on individual HTML tags. Note that if you want to programmatically generate the extra_css override
the get_extra_css() (page 41) method instead. For example:
extra_css = '.heading { font: serif x-large }'
feeds = None
List of feeds to download. Can be either [url1, url2, ...] or [('title1', url1), ('ti-
tle2', url2),...]
filter_regexps = []
List of regular expressions that determines which links to ignore. If empty it is ignored. Used only if
is_link_wanted is not implemented. For example:
filter_regexps = [r'ads\.doubleclick\.net']
will remove all URLs that have ads.doubleclick.net in them.
Only one of BasicNewsRecipe.match_regexps (page 46) or BasicNewsRecipe.
filter_regexps (page 46) should be dened.
handle_gzip = True
Set to False if you do not want to use gzipped transfers with the mechanize browser. Note that some old
servers ake out with gzip.
ignore_duplicate_articles = None
Ignore duplicates of articles that are present in more than one section. A duplicate article is an article that has
the same title and/or URL. To ignore articles with the same title, set this to:
ignore_duplicate_articles = {'title'}
To use URLs instead, set it to:
ignore_duplicate_articles = {'url'}
To match on title or URL, set it to:
ignore_duplicate_articles = {'title', 'url'}
keep_only_tags = []
Keep only the specied tags and their children. For the format for specifying a tag see BasicNewsRecipe.
remove_tags (page 48). If this list is not empty, then the <body> tag will be emptied and re-lled with
the tags that match the entries in this list. For example:
keep_only_tags = [dict(id=['content', 'heading'])]
will keep only tags that have an id attribute of “content” or “heading”.
language = 'und'
The language that the news is in. Must be an ISO-639 code either two or three characters long
masthead_url = None
By default, calibre will use a default image for the masthead (Kindle only). Override this in your recipe to
provide a URL to use as a masthead.
match_regexps = []
List of regular expressions that determines which links to follow. If empty, it is ignored. Used only if
is_link_wanted is not implemented. For example:
46 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
match_regexps = [r'page=[0-9]+']
will match all URLs that have page=some number in them.
Only one of BasicNewsRecipe.match_regexps (page 46) or BasicNewsRecipe.
filter_regexps (page 46) should be dened.
max_articles_per_feed = 100
Maximum number of articles to download from each feed. This is primarily useful for feeds that don’t have
article dates. For most feeds, you should use BasicNewsRecipe.oldest_article (page 47)
needs_subscription = False
If True the GUI will ask the user for a username and password to use while downloading. If set to “optional”
the use of a username and password becomes optional
no_stylesheets = False
Convenient ag to disable loading of stylesheets for websites that have overly complex stylesheets unsuitable
for conversion to e-book formats. If True stylesheets are not downloaded and processed
oldest_article = 7.0
Oldest article to download from this news source. In days.
preprocess_regexps = []
List of regexp substitution rules to run on the downloaded HTML. Each element of the list should be a two
element tuple. The rst element of the tuple should be a compiled regular expression and the second a callable
that takes a single match object and returns a string to replace the match. For example:
preprocess_regexps = [
(re.compile(r'<!--Article ends here-->.*</body>', re.DOTALL|re.IGNORECASE),
lambda match: '</body>'),
]
will remove everything from <!–Article ends here–> to </body>.
publication_type = 'unknown'
Publication type Set to newspaper, magazine or blog. If set to None, no publication type metadata will be
written to the opf le.
recipe_disabled = None
Set to a non empty string to disable this recipe. The string will be used as the disabled message
recipe_specific_options = None
Specify options specic to this recipe. These will be available for the user to customize in the Advanced tab
of the Fetch News dialog or at the ebook-convert command line. The options are specied as a dictionary
mapping option name to metadata about the option. For example:
recipe_specific_options = {
'edition_date': {
'short': 'The issue date to download',
'long': 'Specify a date in the format YYYY-mm-dd to download the
,issue corresponding to that date',
'default': 'current',
}
}
When the recipe is run, self.recipe_specic_options will be a dict mapping option name to the option value
specied by the user. When the option is unspecied by the user, it will have the value specied by ‘default’.
If no default is specied, the option will not be in the dict at all, when unspecied by the user.
2.5. API documentation 47
calibre User Manual, Release 7.19.0
recursions = 0
Number of levels of links to follow on article webpages
remove_attributes = []
List of attributes to remove from all tags. For example:
remove_attributes = ['style', 'font']
remove_empty_feeds = False
If True empty feeds are removed from the output. This option has no eect if parse_index is overridden in
the sub class. It is meant only for recipes that return a list of feeds using feeds or get_feeds() (page 41).
It is also used if you use the ignore_duplicate_articles option.
remove_javascript = True
Convenient ag to strip all JavaScript tags from the downloaded HTML
remove_tags = []
List of tags to be removed. Specied tags are removed from downloaded HTML. A tag is specied as a
dictionary of the form:
{
name : 'tag name', #e.g. 'div'
attrs : a dictionary, #e.g. {'class': 'advertisment'}
}
All keys are optional. For a full explanation of the search criteria, see Beautiful Soup
24
A common example:
remove_tags = [dict(name='div', class_='advert')]
This will remove all <div class=”advert”> tags and all their children from the downloaded HTML.
remove_tags_after = None
Remove all tags that occur after the specied tag. For the format for specifying a tag see
BasicNewsRecipe.remove_tags (page 48). For example:
remove_tags_after = [dict(id='content')]
will remove all tags after the rst element with id=”content”.
remove_tags_before = None
Remove all tags that occur before the specied tag. For the format for specifying a tag see
BasicNewsRecipe.remove_tags (page 48). For example:
remove_tags_before = dict(id='content')
will remove all tags before the rst element with id=”content”.
requires_version = (0, 6, 0)
Minimum calibre version needed to use this recipe
resolve_internal_links = False
If set to True then links in downloaded articles that point to other downloaded articles are changed to point
to the downloaded copy of the article rather than its original web URL. If you set this to True, you might
also need to implement canonicalize_internal_url() (page 40) to work with the URL scheme
of your particular website.
48 Chapter 2. Adding your favorite news website
calibre User Manual, Release 7.19.0
reverse_article_order = False
Reverse the order of articles in each feed
scale_news_images = None
Maximum dimensions (w,h) to scale images to. If scale_news_images_to_device is True this is set to the
device screen dimensions set by the output prole unless there is no prole set, in which case it is left at
whatever value it has been assigned (default None).
scale_news_images_to_device = True
Rescale images to t in the device screen dimensions set by the output prole. Ignored if no output prole is
set.
simultaneous_downloads = 5
Number of simultaneous downloads. Set to 1 if the server is picky. Automatically reduced to 1 if
BasicNewsRecipe.delay (page 45) > 0
summary_length = 500
Max number of characters in the short description
template_css = '\n .article_date {\n color: gray; font-family:
monospace;\n }\n\n .article_description {\n text-indent: 0pt;\n }\n\n
a.article {\n font-weight: bold; text-align:left;\n }\n\n a.feed {\n
font-weight: bold;\n }\n\n .calibre_navbar {\n font-family:monospace;\n
}\n '
The CSS that is used to style the templates, i.e., the navigation bars and the Tables of Contents. Rather than
overriding this variable, you should use extra_css in your recipe to customize look and feel.
timefmt = ' [%a, %d %b %Y]'
The format string for the date shown on the rst page. By default: Day_Name, Day_Number Month_Name
Year
timeout = 120.0
Timeout for fetching les from server in seconds
title = 'Unknown News Source'
The title to use for the e-book
use_embedded_content = None
Normally we try to guess if a feed has full articles embedded in it based on the length of the embedded content.
If None, then the default guessing is used. If True then the we always assume the feeds has embedded content
and if False we always assume the feed does not have embedded content.
14
https://pythonhosted.org/feedparser/
15
https://pythonhosted.org/feedparser/reference-entry-link.html
16
https://mechanize.readthedocs.io/en/latest/
17
https://www.crummy.com/software/BeautifulSoup/bs4/doc
18
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
19
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
20
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
21
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
22
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
23
https://www.imagemagick.org/script/color.php
24
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-the-tree
2.5. API documentation 49
calibre User Manual, Release 7.19.0
50 Chapter 2. Adding your favorite news website
CHAPTER
THREE
THE E-BOOK VIEWER
calibre includes a built-in E-book viewer that can view all the major e-book formats. The E-book viewer is highly cus-
tomizable and has many advanced features.
Starting the E-book viewer (page 51)
Navigating around an e-book (page 52)
Highlighting text (page 53)
Read aloud (page 53)
Searching the text (page 54)
Following links using only the keyboard (page 54)
Customizing the look and feel of your reading experience (page 54)
Dictionary lookup (page 55)
Copying text and images (page 55)
Zooming in on images (page 55)
Syncing with a paper edition of the current book (page 55)
Keyboard shortcuts (page 55)
Non re-owable content (page 58)
Designing your book to work well with the calibre E-book viewer (page 58)
3.1 Starting the E-book viewer
You can view any of the books in your calibre library by selecting the book and pressing the View button. This will open
up the book in the E-book viewer. You can also launch the E-book viewer by itself from the Start menu in Windows. On
macOS, you can pin it to the dock and launch it from there. On Linux you can use its launcher in the desktop menus or
run the command ebook-viewer.
51
calibre User Manual, Release 7.19.0
3.2 Navigating around an e-book
You can “turn pages” in a book by either:
Clicking in the left or right margin or the page with the mouse
Pressing the spacebar, page up, page down or arrow keys
On a touchscreen tapping on the text or swiping left and right
You can access the viewer controls by either:
Right clicking on the text
Pressing the Esc or Menu keys
On a touchscreen by tapping the top 1/3rd of the screen
The viewer has two modes, “paged” and “ow”. In paged mode the book content is presented as pages, similar to a paper
book. In ow mode the text is presented continuously, like in a web browser. You can switch between them using the
viewer Preferences under Page layout or by pressing the Ctrl+M key.
3.2.1 Bookmarks
When you are in the middle of a book and close the E-book viewer, it will remember where you stopped reading and
return there the next time you open the book. You can also set bookmarks in the book by using the Bookmarks button
in the E-book viewer controls or pressing Ctrl+B. When viewing EPUB format books, these bookmarks are actually
saved in the EPUB le itself. You can add bookmarks, then send the le to a friend. When they open the le, they will
be able to see your bookmarks. You can turn o this behavior in the Miscellaneous section of the viewer preferences.
3.2.2 Table of Contents
If the book you are reading denes a Table of Contents, you can access it by pressing the Table of Contents button. This
will bring up a list of sections in the book. You can click on any of them to jump to that portion of the book.
3.2.3 Navigating by location
E-books, unlike paper books, have no concept of pages. You can refer to precise locations in e-books using the Go
to → Location functionality in the viewer controls.
You can use this location information to unambiguously refer to parts of the books when discussing it with friends or
referring to it in other works. You can enter these locations under Go to → Location in the viewer controls.
There is a URL you can copy to the clipboard and paste into other programs or documents. Clicking on this URL will
open the book in the calibre E-book viewer at the current location.
If you click on links inside the e-book to take you to dierent parts of the book, such as an endnote, you can use the Back
and Forward buttons in the top left corner of the viewer controls. These buttons behave just like those in a web browser.
52 Chapter 3. The E-book viewer
calibre User Manual, Release 7.19.0
3.2.4 Reference mode
calibre also has a very handy Reference mode. You can turn it on by clicking the Reference mode button in the viewer
controls. Once you do this, every paragraph will have a unique number displayed at the start, made up of the section and
paragraph numbers.
You can use this number to unambiguously refer to parts of the books when discussing it with friends or referring to it in
other works. You can enter these numbers in the Go to function to navigate to a particular reference location.
3.3 Highlighting text
When you select text in the viewer, a little popup bar appears next to the selection. You can click the highlight button
in that bar to create a highlight. You can add notes and change the color of the highlight. On a touch screen, long tap
a word to select it and show the popup bar. Once in highlight mode you can change what text is selected, using touch
screen friendly selection handles. Drag the handles to the top or bottom margins to scroll while selecting. You can also
Shift+click or right click to extend the selection, particularly useful for multi-page selections.
You can use the Highlights button in the viewer controls to show a separate panel with a list of all highlights in the book,
sorted by chapter.
You can browse all highlights in your entire calibre library by right clicking the View button and choosing Browse anno-
tations.
Finally, if you use the calibre Content server’s in browser viewer, you can have the viewer sync its annotations with
the browser viewer by going to Preferences → Miscellaneous in the viewer preferences and entering the username of the
Content server viewer to sync with. Use the special value * to sync with anonymous users.
3.4 Read aloud
The viewer can read book text aloud. To use it you can simply click the Read aloud button in the viewer controls to start
reading book text aloud. The word being currently read is highlighted. Speech is synthesized from the text using your
operating system services for text-to-speech. You can change the voice being used by clicking the gear icon in the bar
that is displayed while Read aloud is active.
You can also read aloud highlighted passages by adding the Read aloud button to the selection bar in the viewer preferences
under Selection behavior.
® Note
Support for text-to-speech in browsers is very incomplete and bug-ridden so how well Read aloud will work in the in-
browser viewer is dependent on how well the underlying browser supports text-to-speech. In particular, highlighting
of current word does not work, and changing speed or voice will cause reading to start again from the beginning.
® Note
On Linux, Read aloud requires Speech Dispatcher
25
to be installed and working.
25
https://freebsoft.org/speechd
3.3. Highlighting text 53
calibre User Manual, Release 7.19.0
® Note
On Windows, not all installed voices may be visible to the SAPI sub-system that is used for text-to-speech. There are
instructions to make all voices visible
26
.
3.5 Searching the text
The viewer has very powerful search capabilities. Press the Ctrl+F key or access the viewer controls and click search.
The simplest form of searching is to just search for whatever text you enter in the text box. The dierent forms of
searching are chosen by the search mode box below the search input. Available modes are:
1. Contains - The simplest default mode. The text entered in the search box is searched for anywhere. All punctuation,
accents and spaces are ignored. For example, the search: Pena will match all of the following: penal, pen
a, pen.a and Peña. If you select the Case sensitive box then accents, spaces and punctuation are no longer
ignored.
2. Whole words - Searches for whole words. So for example, the search pena will match the word Peña but not the
word Penal. As with Contains searches above, accents and punctuation are ignored unless the Case sensitive box
is checked.
3. Nearby words - Searches for whole words that are near each other. So for example, the search calibre cool
will match places where the words calibre and cool occur within sixty characters of each other. To change
the number of characters add the new number to the end of the list of words. For instance, calibre cool
awesome 120 will match places where the three words occur within 120 characters of each other. Note that
punctuation and accents are not ignored for these searches.
4. Regex - Interprets the search text as a regular expression. To learn more about using regular expressions, see the
tutorial (page 215).
3.6 Following links using only the keyboard
The E-book viewer has a Hints mode that allows you to click links in the text without using the mouse. Press the Alt+F
key and all links in the current screen will be highlighted with a number or letter over them. Press the letter on your
keyboard to click the link. Pressing the Esc key will abort the Hints mode without selecting any link.
If more than thirty ve links are on-screen then some of them will have multiple letters, in which case type the rst and
second, or the rst and press Enter to activate. You can also use the Backspace key to undo a mistake in typing.
3.7 Customizing the look and feel of your reading experience
You can change font sizes on the y by using Font size in the viewer controls or Ctrl++ or Ctrl+- or holding the Ctrl
key and using the mouse wheel.
Colors can be changed in the Colors section of the viewer preferences.
You can change the number of pages displayed on the screen as well as page margins in Page layout in the viewer pref-
erences.
You can display custom headers and footers such as time left to read, current chapter title, book position, etc. via the
Headers and footers section of the viewer preferences.
26
https://www.mobileread.com/forums/showpost.php?p=4084051&postcount=108
54 Chapter 3. The E-book viewer
calibre User Manual, Release 7.19.0
More advanced customization can be achieved by the Styles settings. Here you can specify a background image to display
under the text and also a stylesheet you can set that will be applied to every book. Using it you can do things like change
paragraph styles, text justication, etc. For examples of custom stylesheets used by calibre’s users, see the forums
27
.
3.8 Dictionary lookup
You can look up the meaning of words in the current book by double clicking or long tapping the word you want to lookup
and then clicking the lookup button that looks like a library.
3.9 Copying text and images
You can select text and images by dragging the content with your mouse and then right clicking and selecting Copy to
copy to the clipboard. The copied material can be pasted into another application as plain text and images.
3.10 Zooming in on images
You can zoom in to show an image at full size in a separate window by either double clicking or long tapping on it. You
can also right click on it and choose View image.
3.11 Syncing with a paper edition of the current book
Some e-books, that have corresponding print editions, include metadata that marks the start of each paper page. For such
e-books, the viewer allows you to jump to a particular paper edition page via the Go to button in the viewer controls. You
can also optionally display the paper page corresponding to the current location in the book’s headers or footers via the
viewer settings, by adding Pages from paper edition to either the header or the footer.
3.12 Keyboard shortcuts
The viewer has extensive keyboard shortcuts, like the rest of calibre. They can be customised in the viewer Preferences.
The default shortcuts are listed below:
Table 1: Keyboard shortcuts for the calibre E-book viewer
Key-
board
short-
cut
Action
Home,
Ctrl+ArrowUp,
Ctrl+ArrowLeft
Scroll to the start of the current le in a multi le book
Ctrl+HomeScroll to the beginning of the book
continues on next page
27
https://www.mobileread.com/forums/showthread.php?t=51500
3.8. Dictionary lookup 55
calibre User Manual, Release 7.19.0
Table 1 continued from previous page
Key-
board
short-
cut
Action
Ctrl+EndScroll to the end of the book
End,
Ctrl+ArrowDown,
Ctrl+ArrowRight
Scroll to the end of the current le in a multi le book
Ar-
rowUp
Scroll backwards, smoothly in ow mode and by screen fulls in paged mode
Ar-
row-
Down
Scroll forwards, smoothly in ow mode and by screen fulls in paged mode
Ar-
rowLeft
Scroll leftwards by a little in ow mode and by a page in paged mode
Ar-
rowRight
Scroll rightwards by a little in ow mode and by a page in paged mode
PageUp,
Shift+Spacebar
Scroll backwards by screen-fulls
PageDown,
Space-
bar
Scroll forwards by screen-fulls
Ctrl+PageUpScroll to the previous section
Ctrl+PageDownScroll to the next section
Alt+ArrowLeftBack
Alt+ArrowRightForward
Ctrl+T Toggle Table of Contents
Ctrl+S Read aloud
Alt+P Change settings quickly by creating and switching to proles
Alt+f Follow links with the keyboard
Ctrl+C Copy to clipboard
Alt+C Copy current location to clipboard
Ctrl+Shift+CCopy current location as calibre:// URL to clipboard
/,
Ctrl+f,
Cmd+f
Start search
F3,
Enter
Find next
Shift+F3,
Shift+Enter
Find previous
Ctrl+Plus,
Meta+Plus
Increase font size
Ctrl+Minus,
Meta+Minus
Decrease font size
Ctrl+0 Restore default font size
continues on next page
56 Chapter 3. The E-book viewer
calibre User Manual, Release 7.19.0
Table 1 continued from previous page
Key-
board
short-
cut
Action
Ctrl+] Increase number of pages per screen
Ctrl+[ Decrease number of pages per screen
Ctrl+Alt+CMake number of pages per screen automatic
F11,
Ctrl+Shift+F
Toggle full screen
Ctrl+M Toggle between Paged mode and Flow mode for text layout
Ctrl+W Toggle the scrollbar
Ctrl+X Toggle the Reference mode
Ctrl+B Show/hide bookmarks
Ctrl+Alt+BNew bookmark
Ctrl+N,
Ctrl+E
Show the book metadata
Ctrl+Alt+F5,
Ctrl+Alt+R
Reload book
Ctrl+Shift+ArrowRightAlter the current selection forward by a word
Ctrl+Shift+ArrowLeftAlter the current selection backwards by a word
Shift+ArrowRightAlter the current selection forward by a character
Shift+ArrowLeftAlter the current selection backwards by a character
Shift+ArrowDownAlter the current selection forward by a line
Shift+HomeExtend the current selection to the start of the line
Shift+EndExtend the current selection to the end of the line
Ctrl+A Select all
Shift+ArrowUpAlter the current selection backwards by a line
Ctrl+Shift+ArrowDownAlter the current selection forward by a paragraph
Ctrl+Shift+ArrowUpAlter the current selection backwards by a paragraph
Esc,
MenuKey
Show the E-book viewer controls
Ctrl+Comma,
Ctrl+Esc,
Meta+Esc,
Meta+Comma
Show E-book viewer preferences
Ctrl+G,
;, :
Go to a specied book location or position
Ctrl+SpacebarToggle auto-scroll
Alt+ArrowUpAuto scroll faster
Alt+ArrowDownAuto scroll slower
Ctrl+I Show/hide Inspector
Ctrl+L Show/hide the word lookup panel
continues on next page
3.12. Keyboard shortcuts 57
calibre User Manual, Release 7.19.0
Table 1 continued from previous page
Key-
board
short-
cut
Action
Ctrl+Q
(Cmd+Q
on
ma-
cOS)
Quit
Ctrl+P Print book to PDF
Ctrl+F11Toggle the toolbar
Ctrl+H Toggle the highlights panel
Ctrl+D Edit this book
3.13 Non re-owable content
Some books have very wide content that cannot be broken up at page boundaries. For example tables or <pre> tags.
In such cases, you should switch the viewer to ow mode by pressing Ctrl+M to read this content. Alternately, you can
also add the following CSS to the Styles section of the viewer preferences to force the viewer to break up lines of text in
<pre> tags:
code, pre { white-space: pre-wrap }
3.14 Designing your book to work well with the calibre E-book viewer
The calibre E-book viewer will set the is-calibre-viewer class on the root element. So you can write CSS rules
that apply only for it. Additionally, the viewer will set the following classes on the body element:
body.calibre-viewer-dark-colors
Set when using a dark color scheme
body.calibre-viewer-light-colors
Set when using a light color scheme
body.calibre-viewer-paginated
Set when in paged mode
body.calibre-viewer-scrolling
Set when in ow (non-paginated) mode
body.calibre-footnote-container
Set when displaying a popup footnote
Finally, you can use the calibre color scheme colors via CSS variables
28
. The calibre E-book viewer denes the fol-
lowing variables: --calibre-viewer-background-color, --calibre-viewer-foreground-color
and optionally --calibre-viewer-link-color in color themes that dene a link color.
28
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
58 Chapter 3. The E-book viewer
CHAPTER
FOUR
E-BOOK CONVERSION
calibre has a conversion system that is designed to be very easy to use. Normally, you just add a book to calibre, click
convert and calibre will try hard to generate output that is as close as possible to the input. However, calibre accepts a
very large number of input formats, not all of which are as suitable as others for conversion to e-books. In the case of
such input formats, or if you just want greater control over the conversion system, calibre has a lot of options to ne tune
the conversion process. Note however that calibre’s conversion system is not a substitute for a full blown e-book editor.
To edit e-books, I recommend rst converting them to EPUB or AZW3 using calibre and then using the Edit book feature
to get them into perfect shape. You can then use the edited e-book as input for conversion into other formats in calibre.
This document will refer mainly to the conversion settings as found in the conversion dialog, pictured below. All these
settings are also available via command line interface to conversion, documented at ebook-convert (page 325). In calibre,
you can obtain help on any individual setting by holding your mouse over it, a tooltip will appear describing the setting.
59
calibre User Manual, Release 7.19.0
Contents
Introduction (page 61)
Look & feel (page 62)
Page setup (page 65)
Heuristic processing (page 65)
Search & replace (page 67)
Structure detection (page 67)
Table of Contents (page 68)
Using images as chapter titles when converting HTML input documents (page 70)
Using tag attributes to supply the text for entries in the Table of Contents (page 70)
How options are set/saved for conversion (page 71)
Format specic tips (page 71)
60 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
4.1 Introduction
The rst thing to understand about the conversion system is that it is designed as a pipeline. Schematically, it looks like
this:
The input format is rst converted to XHTML by the appropriate Input plugin. This HTML is then transformed. In the
last step, the processed XHTML is converted to the specied output format by the appropriate Output plugin. The results
of the conversion can vary greatly, based on the input format. Some formats convert much better than others. A list of
the best source formats for conversion is available here (page 130).
The transforms that act on the XHTML output are where all the work happens. There are various transforms, for example,
to insert book metadata as a page at the start of the book, to detect chapter headings and automatically create a Table
4.1. Introduction 61
calibre User Manual, Release 7.19.0
of Contents, to proportionally adjust font sizes, et cetera. It is important to remember that all the transforms act on the
XHTML output by the Input plugin, not on the input le itself. So, for example, if you ask calibre to convert an RTF le
to EPUB, it will rst be converted to XHTML internally, the various transforms will be applied to the XHTML and then
the Output plugin will create the EPUB le, automatically generating all metadata, Table of Contents, et cetera.
You can see this process in action by using the debug option . Just specify the path to a folder for the
debug output. During conversion, calibre will place the XHTML generated by the various stages of the conversion pipeline
in dierent sub-folders. The four sub-folders are:
Table 1: Stages of the conversion pipeline
Folder Description
input This contains the HTML output by the Input plugin. Use this to debug the Input plugin.
parsed The result of pre-processing and converting to XHTML the output from the Input plugin. Use to debug
structure detection.
struc-
ture
Post structure detection, but before CSS attening and font size conversion. Use to debug font size conver-
sion and CSS transforms.
pro-
cessed
Just before the e-book is passed to the Output plugin. Use to debug the Output plugin.
If you want to edit the input document a little before having calibre convert it, the best thing to do is edit the les in the
input sub-folder, then zip it up, and use the ZIP le as the input format for subsequent conversions. To do this use the
Edit meta information dialog to add the ZIP le as a format for the book and then, in the top left corner of the conversion
dialog, select ZIP as the input format.
This document will deal mainly with the various transforms that operate on the intermediate XHTML and how to control
them. At the end are some tips specic to each input/output format.
4.2 Look & feel
Contents
Fonts (page 63)
Text (page 64)
Layout (page 64)
Styling (page 64)
Transform styles (page 65)
Transform HTML (page 65)
This group of options controls various aspects of the look and feel of the converted e-book.
62 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
4.2.1 Fonts
One of the nicest features of the e-reading experience is the ability to easily adjust font sizes to suit individual needs and
lighting conditions. calibre has sophisticated algorithms to ensure that all the books it outputs have a consistent font sizes,
no matter what font sizes are specied in the input document.
The base font size of a document is the most common font size in that document, i.e., the size of the bulk of text in that
document. When you specify a Base font size, calibre automatically rescales all font sizes in the document proportionately,
so that the most common font size becomes the specied base font size and other font sizes are rescaled appropriately.
By choosing a larger base font size, you can make the fonts in the document larger and vice versa. When you set the base
font size, for best results, you should also set the font size key.
Normally, calibre will automatically choose a base font size appropriate to the output prole you have chosen (see Page
setup (page 65)). However, you can override this here in case the default is not suitable for you.
The Font size key option lets you control how non-base font sizes are rescaled. The font rescaling algorithm works using a
font size key, which is simply a comma-separated list of font sizes. The font size key tells calibre how many “steps” bigger
or smaller a given font size should be compared to the base font size. The idea is that there should be a limited number
of font sizes in a document. For example, one size for the body text, a couple of sizes for dierent levels of headings and
a couple of sizes for super/sub scripts and footnotes. The font size key allows calibre to compartmentalize the font sizes
in the input documents into separate “bins” corresponding to the dierent logical font sizes.
Let’s illustrate with an example. Suppose the source document we are converting was produced by someone with excellent
eyesight and has a base font size of 8pt. That means the bulk of the text in the document is sized at 8pts, while headings
are somewhat larger (say 10 and 12pt) and footnotes somewhat smaller at 6pt. Now if we use the following settings:
Base font size : 12pt
Font size key : 7, 8, 10, 12, 14, 16, 18, 20
The output document will have a base font size of 12pt, headings of 14 and 16pt and footnotes of 8pt. Now suppose we
want to make the largest heading size stand out more and make the footnotes a little larger as well. To achieve this, the
font key should be changed to:
New font size key : 7, 9, 12, 14, 18, 20, 22
The largest headings will now become 18pt, while the footnotes will become 9pt. You can play with these settings to try
and gure out what would be optimum for you by using the font rescaling wizard, which can be accessed by clicking the
little button next to the Font size key setting.
All the font size rescaling in the conversion can also be disabled here, if you would like to preserve the font sizes in the
input document.
A related setting is Line height. Line height controls the vertical height of lines. By default, (a line height of 0), no
manipulation of line heights is performed. If you specify a non-default value, line heights will be set in all locations that
don’t specify their own line heights. However, this is something of a blunt weapon and should be used sparingly. If you
want to adjust the line heights for some section of the input, it’s better to use the Extra CSS (page 64).
In this section you can also tell calibre to embed any referenced fonts into the book. This will allow the fonts to work on
reader devices even if they are not available on the device.
4.2. Look & feel 63
calibre User Manual, Release 7.19.0
4.2.2 Text
Text can be either justied or not. Justied text has extra spaces between words to give a smooth right margin. Some
people prefer justied text, others do not. Normally, calibre will preserve the justication in the original document. If
you want to override it you can use the
Text justication
option in this section.
You can also tell calibre to Smarten punctuation which will replace plain quotes, dashes and ellipses with their typograph-
ically correct alternatives. Note that this algorithm is not perfect so it is worth reviewing the results. The reverse, namely,
Unsmarted punctuation is also available.
Finally, there is Input character encoding. Older documents sometimes don’t specify their character encoding. When
converted, this can result in non-English characters or special characters like smart quotes being corrupted. calibre tries
to auto-detect the character encoding of the source document, but it does not always succeed. You can force it to assume a
particular character encoding by using this setting. cp1252 is a common encoding for documents produced using Windows
software. You should also read How do I convert my le containing non-English characters, or smart quotes? (page 130)
for more on encoding issues.
4.2.3 Layout
Normally, paragraphs in XHTML are rendered with a blank line between them and no leading text indent. calibre has a
couple of options to control this. Remove spacing between paragraphs forcefully ensure that all paragraphs have no inter
paragraph spacing. It also sets the text indent to 1.5em (can be changed) to mark the start of every paragraph. Insert
blank line does the opposite, guaranteeing that there is exactly one blank line between each pair of paragraphs. Both these
options are very comprehensive, removing spacing, or inserting it for all paragraphs (technically <p> and <div> tags).
This is so that you can just set the option and be sure that it performs as advertised, irrespective of how messy the input
le is. The one exception is when the input le uses hard line breaks to implement inter-paragraph spacing.
If you want to remove the spacing between all paragraphs, except a select few, don’t use these options. Instead add the
following CSS code to Extra CSS (page 64):
p, div { margin: 0pt; border: 0pt; text-indent: 1.5em }
.spacious { margin-bottom: 1em; text-indent: 0pt; }
Then, in your source document, mark the paragraphs that need spacing with class=”spacious”. If your input document is
not in HTML, use the Debug option, described in the Introduction to get HTML (use the input sub-folder).
Another useful options is Linearize tables. Some badly designed documents use tables to control the layout of text on the
page. When converted these documents often have text that runs o the page and other artifacts. This option will extract
the content from the tables and present it in a linear fashion. Note that this option linearizes all tables, so only use it if
you are sure the input document does not use tables for legitimate purposes, like presenting tabular information.
4.2.4 Styling
The Extra CSS option allows you to specify arbitrary CSS that will be applied to all HTML les in the input. This CSS is
applied with very high priority and so should override most CSS present in the input document itself. You can use this
setting to ne tune the presentation/layout of your document. For example, if you want all paragraphs of class endnote to
be right aligned, just add:
.endnote { text-align: right }
or if you want to change the indentation of all paragraphs:
p { text-indent: 5mm; }
64 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
Extra CSS is a very powerful option, but you do need an understanding of how CSS works to use it to its full potential.
You can use the debug pipeline option described above to see what CSS is present in your input document.
A simpler option is to use Filter style information. This allows you to remove all CSS properties of the specied types
from the document. For example, you can use it to remove all colors or fonts.
4.2.5 Transform styles
This is the most powerful styling related facility. You can use it to dene rules that change styles based on various
conditions. For example you can use it to change all green colors to blue, or remove all bold styling from the text or color
all headings a certain color, etc.
4.2.6 Transform HTML
Similar to transform styles, but allows you to make changes to the HTML content of the book. You can replace one tag
with another, add classes or other attributes to tags based on their content, etc.
4.3 Page setup
The Page setup options are for controlling screen layout, like margins and screen sizes. There are options to setup page
margins, which will be used by the output plugin, if the selected output format supports page margins. In addition, you
should choose an Input prole and an output prole. Both sets of proles basically deal with how to interpret measurements
in the input/output documents, screen sizes and default font rescaling keys.
If you know that the le you are converting was intended to be used on a particular device/software platform, choose the
corresponding input prole, otherwise just choose the default input prole. If you know the les you are producing are
meant for a particular device type, choose the corresponding output prole. Otherwise, choose one of the Generic output
proles. If you are converting to MOBI or AZW3 then you will almost always want to choose one of the Kindle output
proles. Otherwise, your best bet for modern E-book reading devices is to choose the Generic e-ink HD output prole.
The output prole also controls the screen size. This will cause, for example, images to be auto-resized to be t to the
screen in some output formats. So choose a prole of a device that has a screen size similar to your device.
4.4 Heuristic processing
Heuristic processing provides a variety of functions which can be used to try and detect and correct common problems
in poorly formatted input documents. Use these functions if your input document suers from poor formatting. Because
these functions rely on common patterns, be aware that in some cases an option may lead to worse results, so use with
care. As an example, several of these options will remove all non-breaking-space entities, or may include false positive
matches relating to the function.
Enable heuristic processing
This option activates calibre’s Heuristic processing stage of the conversion pipeline. This must be enabled in order
for various sub-functions to be applied
Unwrap lines
Enabling this option will cause calibre to attempt to detect and correct hard line breaks that exist within a document
using punctuation clues and line length. calibre will rst attempt to detect whether hard line breaks exist, if they
do not appear to exist calibre will not attempt to unwrap lines. The line-unwrap factor can be reduced if you want
to ‘force’ calibre to unwrap lines.
4.3. Page setup 65
calibre User Manual, Release 7.19.0
Line-unwrap factor
This option controls the algorithm calibre uses to remove hard line breaks. For example, if the value of this option
is 0.4, that means calibre will remove hard line breaks from the end of lines whose lengths are less than the length
of 40% of all lines in the document. If your document only has a few line breaks which need correction, then this
value should be reduced to somewhere between 0.1 and 0.2.
Detect and markup unformatted chapter headings and sub headings
If your document does not have chapter headings and titles formatted dierently from the rest of the text, calibre
can use this option to attempt to detect them and surround them with heading tags. <h2> tags are used for chapter
headings; <h3> tags are used for any titles that are detected.
This function will not create a TOC, but in many cases it will cause calibre’s default chapter detection settings to
correctly detect chapters and build a TOC. Adjust the XPath under Structure detection if a TOC is not automatically
created. If there are no other headings used in the document then setting “//h:h2” under Structure detection would
be the easiest way to create a TOC for the document.
The inserted headings are not formatted, to apply formatting use the Extra CSS option under the Look and Feel
conversion settings. For example, to center heading tags, use the following:
h2, h3 { text-align: center }
Renumber sequences of <h1> or <h2> tags
Some publishers format chapter headings using multiple <h1> or <h2> tags sequentially. calibre’s default conversion
settings will cause such titles to be split into two pieces. This option will re-number the heading tags to prevent
splitting.
Delete blank lines between paragraphs
This option will cause calibre to analyze blank lines included within the document. If every paragraph is interleaved
with a blank line, then calibre will remove all those blank paragraphs. Sequences of multiple blank lines will be
considered scene breaks and retained as a single paragraph. This option diers from the Remove paragraph spacing
option under Look and Feel in that it actually modies the HTML content, while the other option modies the
document styles. This option can also remove paragraphs which were inserted using calibre’s Insert blank line
option.
Ensure scene breaks are consistently formatted
With this option calibre will attempt to detect common scene-break markers and ensure that they are center aligned.
‘Soft’ scene break markers, i.e. scene breaks only dened by extra white space, are styled to ensure that they will
not be displayed in conjunction with page breaks.
Replace scene breaks
If this option is congured then calibre will replace scene break markers it nds with the replacement text specied
by the user. Please note that some ornamental characters may not be supported across all reading devices.
In general you should avoid using HTML tags, calibre will discard any tags and use pre-dened markup. <hr />
tags, i.e. horizontal rules, and <img> tags are exceptions. Horizontal rules can optionally be specied with styles,
if you choose to add your own style be sure to include the ‘width’ setting, otherwise the style information will be
discarded. Image tags can used, but calibre does not provide the ability to add the image during conversion, this
must be done after the fact using the ‘Edit book’ feature.
Example image tag (place the image within an ‘Images’ folder inside the EPUB after
conversion):
<img style=”width:10%” src=”../Images/scenebreak.png” />
Example horizontal rule with styles:
<hr style=”width:20%;padding-top: 1px;border-top: 2px ridge black;border-bottom: 2px groove
black;”/>
Remove unnecessary hyphens
calibre will analyze all hyphenated content in the document when this option is enabled. The document itself is
66 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
used as a dictionary for analysis. This allows calibre to accurately remove hyphens for any words in the document
in any language, along with made-up and obscure scientic words. The primary drawback is words appearing only
a single time in the document will not be changed. Analysis happens in two passes, the rst pass analyzes line
endings. Lines are only unwrapped if the word exists with or without a hyphen in the document. The second pass
analyzes all hyphenated words throughout the document, hyphens are removed if the word exists elsewhere in the
document without a match.
Italicize common words and patterns
When enabled, calibre will look for common words and patterns that denote italics and italicize them. Examples
are common text conventions such as ~word~ or phrases that should generally be italicized, e.g. latin phrases like
‘etc.’ or ‘et cetera’.
Replace entity indents with CSS indents
Some documents use a convention of dening text indents using non-breaking space entities. When this option is
enabled calibre will attempt to detect this sort of formatting and convert them to a 3% text indent using CSS.
4.5 Search & replace
These options are useful primarily for conversion of PDF documents or OCR conversions, though they can also be used
to x many document specic problems. As an example, some conversions can leaves behind page headers and footers
in the text. These options use regular expressions to try and detect headers, footers, or other arbitrary text and remove or
replace them. Remember that they operate on the intermediate XHTML produced by the conversion pipeline. There is
a wizard to help you customize the regular expressions for your document. Click the magic wand beside the expression
box, and click the ‘Test’ button after composing your search expression. Successful matches will be highlighted in Yellow.
The search works by using a Python regular expression. All matched text is simply removed from the document or
replaced using the replacement pattern. The replacement pattern is optional, if left blank then text matching the search
pattern will be deleted from the document. You can learn more about regular expressions and their syntax at All about
using regular expressions in calibre (page 215).
4.6 Structure detection
Structure detection involves calibre trying its best to detect structural elements in the input document, when they are not
properly specied. For example, chapters, page breaks, headers, footers, etc. As you can imagine, this process varies
widely from book to book. Fortunately, calibre has very powerful options to control this. With power comes complexity,
but if once you take the time to learn the complexity, you will nd it well worth the eort.
4.6.1 Chapters and page breaks
calibre has two sets of options for chapter detection and inserting page breaks. This can sometimes be slightly confusing,
as by default, calibre will insert page breaks before detected chapters as well as the locations detected by the page breaks
option. The reason for this is that there are often location where page breaks should be inserted that are not chapter
boundaries. Also, detected chapters can be optionally inserted into the auto generated Table of Contents.
calibre uses XPath, a powerful language to allow the user to specify chapter boundaries/page breaks. XPath can seem a
little daunting to use at rst, fortunately, there is a XPath tutorial (page 158) in the User Manual. Remember that Structure
detection operates on the intermediate XHTML produced by the conversion pipeline. Use the debug option described in
the Introduction (page 61) to gure out the appropriate settings for your book. There is also a button for a XPath wizard
to help with the generation of simple XPath expressions.
By default, calibre uses the following expression for detecting chapters:
4.5. Search & replace 67
calibre User Manual, Release 7.19.0
//*[((name()='h1' or name()='h2') and re:test(., 'chapter|book|section|part\s+', 'i
,')) or @class = 'chapter']
This expression is rather complex, because it tries to handle a number of common cases simultaneously. What it means
is that calibre will assume chapters start at either <h1> or <h2> tags that have any of the words (chapter, book, section or
part) in them or that have the class=”chapter” attribute.
A related option is Chapter mark, which allows you to control what calibre does when it detects a chapter. By default, it
will insert a page break before the chapter. You can have it insert a ruled line instead of, or in addition to the page break.
You can also have it do nothing.
The default setting for detecting page breaks is:
//*[name()='h1' or name()='h2']
which means that calibre will insert page breaks before every <h1> and <h2> tag by default.
® Note
The default expressions may change depending on the input format you are converting.
4.6.2 Miscellaneous
There are a few more options in this section.
Insert metadata as page at start of book
One of the great things about calibre is that it allows you to maintain very complete metadata about all of your
books, for example, a rating, tags, comments, etc. This option will create a single page with all this metadata and
insert it into the converted e-book, typically just after the cover. Think of it as a way to create your own customised
book jacket.
Remove rst image
Sometimes, the source document you are converting includes the cover as part of the book, instead of as a separate
cover. If you also specify a cover in calibre, then the converted book will have two covers. This option will simply
remove the rst image from the source document, thereby ensuring that the converted book has only one cover, the
one specied in calibre.
4.7 Table of Contents
When the input document has a Table of Contents in its metadata, calibre will just use that. However, a number of older
formats either do not support a metadata based Table of Contents, or individual documents do not have one. In these
cases, the options in this section can help you automatically generate a Table of Contents in the converted e-book, based
on the actual content in the input document.
® Note
Using these options can be a little challenging to get exactly right. If you prefer creating/editing the Table of Contents
by hand, convert to the EPUB or AZW3 formats and select the checkbox at the bottom of the Table of Contents
section of the conversion dialog that says Manually ne-tune the Table of Contents after conversion. This will launch
the ToC Editor tool after the conversion. It allows you to create entries in the Table of Contents by simply clicking
the place in the book where you want the entry to point. You can also use the ToC Editor by itself, without doing a
68 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
conversion. Go to Preferences → Interface → Toolbars and add the ToC Editor to the main toolbar. Then just select
the book you want to edit and click the ToC Editor button.
The rst option is Force use of auto-generated Table of Contents. By checking this option you can have calibre override
any Table of Contents found in the metadata of the input document with the auto generated one.
The default way that the creation of the auto generated Table of Contents works is that, calibre will rst try to add any
detected chapters to the generated table of contents. You can learn how to customize the detection of chapters in the
Structure detection (page 67) section above. If you do not want to include detected chapters in the generated table of
contents, check the Do not add detected chapters option.
If less than the Chapter threshold number of chapters were detected, calibre will then add any hyperlinks it nds in the
input document to the Table of Contents. This often works well: many input documents include a hyperlinked Table of
Contents right at the start. The Number of links option can be used to control this behavior. If set to zero, no links are
added. If set to a number greater than zero, at most that number of links is added.
calibre will automatically lter duplicates from the generated Table of Contents. However, if there are some additional
undesirable entries, you can lter them using the TOC Filter option. This is a regular expression that will match the title
of entries in the generated table of contents. Whenever a match is found, it will be removed. For example, to remove all
entries titles “Next” or “Previous” use:
Next|Previous
The Level 1,2,3 TOC options allow you to create a sophisticated multi-level Table of Contents. They are XPath expressions
that match tags in the intermediate XHTML produced by the conversion pipeline. See the Introduction (page 61) for how
to get access to this XHTML. Also read the XPath tutorial (page 158), to learn how to construct XPath expressions. Next
to each option is a button that launches a wizard to help with the creation of basic XPath expressions. The following
simple example illustrates how to use these options.
Suppose you have an input document that results in XHTML that look like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample document</title>
</head>
<body>
<h1>Chapter 1</h1>
...
<h2>Section 1.1</h2>
...
<h2>Section 1.2</h2>
...
<h1>Chapter 2</h1>
...
<h2>Section 2.1</h2>
...
</body>
</html>
Then, we set the options as:
Level 1 TOC : //h:h1
Level 2 TOC : //h:h2
This will result in an automatically generated two level Table of Contents that looks like:
4.7. Table of Contents 69
calibre User Manual, Release 7.19.0
Chapter 1
Section 1.1
Section 1.2
Chapter 2
Section 2.1
Á Warning
Not all output formats support a multi level Table of Contents. You should rst try with EPUB output. If that works,
then try your format of choice.
4.8 Using images as chapter titles when converting HTML input doc-
uments
Suppose you want to use an image as your chapter title, but still want calibre to be able to automatically generate a Table
of Contents for you from the chapter titles. Use the following HTML markup to achieve this:
<html>
<body>
<h2>Chapter 1</h2>
<p>chapter 1 text...</p>
<h2 title="Chapter 2"><img src="chapter2.jpg" /></h2>
<p>chapter 2 text...</p>
</body>
</html>
Set the Level 1 TOC setting to //h:h2. Then, for chapter two, calibre will take the title from the value of the title
attribute on the <h2> tag, since the tag has no text.
4.9 Using tag attributes to supply the text for entries in the Table of
Contents
If you have particularly long chapter titles and want shortened versions in the Table of Contents, you can use the title
attribute to achieve this, for example:
<html>
<body>
<h2 title="Chapter 1">Chapter 1: Some very long title</h2>
<p>chapter 1 text...</p>
<h2 title="Chapter 2">Chapter 2: Some other very long title</h2>
<p>chapter 2 text...</p>
</body>
</html>
Set the Level 1 TOC setting to //h:h2/@title. Then calibre will take the title from the value of the title attribute
on the <h2> tags, instead of using the text inside the tag. Note the trailing /@title on the XPath expression, you can
use this form to tell calibre to get the text from any attribute you like.
70 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
4.10 How options are set/saved for conversion
There are two places where conversion options can be set in calibre. The rst is in Preferences->Conversion. These
settings are the defaults for the conversion options. Whenever you try to convert a new book, the settings set here will be
used by default.
You can also change settings in the conversion dialog for each book conversion. When you convert a book, calibre
remembers the settings you used for that book, so that if you convert it again, the saved settings for the individual book
will take precedence over the defaults set in Preferences. You can restore the individual settings to defaults by using the
Restore defaults button in the individual book conversion dialog. You can remove the saved settings for a group of books
by selecting all the books and then clicking the Edit metadata button to bring up the bulk metadata edit dialog, near the
bottom of the dialog is an option to remove stored conversion settings.
When you bulk convert a set of books, settings are taken in the following order (last one wins):
From the defaults set in Preferences->Conversion
From the saved conversion settings for each book being converted (if any). This can be turned o by the option in
the top left corner of the Bulk conversion dialog.
From the settings set in the Bulk conversion dialog
Note that the nal settings for each book in a Bulk conversion will be saved and re-used if the book is converted again.
Since the highest priority in Bulk Conversion is given to the settings in the Bulk conversion dialog, these will override
any book specic settings. So you should only bulk convert books together that need similar settings. The exceptions
are metadata and input format specic settings. Since the Bulk conversion dialog does not have settings for these two
categories, they will be taken from book specic settings (if any) or the defaults.
® Note
You can see the actual settings used during any conversion by clicking the rotating icon in the lower right corner and
then double clicking the individual conversion job. This will bring up a conversion log that will contain the actual
settings used, near the top.
4.11 Format specic tips
Here you will nd tips specic to the conversion of particular formats. Options specic to particular format, whether
input or output are available in the conversion dialog under their own section, for example TXT input or EPUB output.
4.11.1 Convert Microsoft Word documents
calibre can automatically convert .docx les created by Microsoft Word 2007 and newer. Just add the le to calibre and
click convert.
® Note
There is a demo .docx le
29
that demonstrates the capabilities of the calibre conversion engine. Just download it and
convert it to EPUB or AZW3 to see what calibre can do.
29
https://calibre-ebook.com/downloads/demos/demo.docx
4.10. How options are set/saved for conversion 71
calibre User Manual, Release 7.19.0
calibre will automatically generate a Table of Contents based on headings if you mark your headings with the Heading
1, Heading 2, etc. styles in Microsoft Word. Open the output e-book in the calibre E-book viewer and click the Table
of Contents button to view the generated Table of Contents.
Older .doc les
For older .doc les, you can save the document as HTML with Microsoft Word and then convert the resulting HTML le
with calibre. When saving as HTML, be sure to use the “Save as Web Page, Filtered” option as this will produce clean
HTML that will convert well. Note that Word produces really messy HTML, converting it can take a long time, so be
patient. If you have a newer version of Word available, you can directly save it as .docx as well.
Another alternative is to use the free LibreOce. Open your .doc le in LibreOce and save it as .docx, which can be
directly converted in calibre.
4.11.2 Convert TXT documents
TXT documents have no well dened way to specify formatting like bold, italics, etc, or document structure like para-
graphs, headings, sections and so on, but there are a variety of conventions commonly used. By default calibre attempts
automatic detection of the correct formatting and markup based on those conventions.
TXT input supports a number of options to dierentiate how paragraphs are detected.
Paragraph style: Auto
Analyzes the text le and attempts to automatically determine how paragraphs are dened. This option
will generally work ne, if you achieve undesirable results try one of the manual options.
Paragraph style: Block
Assumes one or more blank lines are a paragraph boundary:
This is the first.
This is the
second paragraph.
Paragraph style: Single
Assumes that every line is a paragraph:
This is the first.
This is the second.
This is the third.
Paragraph style: Print
Assumes that every paragraph starts with an indent (either a tab or 2+ spaces). Paragraphs end when
the next line that starts with an indent is reached:
This is the
first.
This is the second.
This is the
third.
Paragraph style: Unformatted
Assumes that the document has no formatting, but does use hard line breaks. Punctuation and median
line length are used to attempt to re-create paragraphs.
72 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
Formatting style: Auto
Attempts to detect the type of formatting markup being used. If no markup is used then heuristic
formatting will be applied.
Formatting style: Heuristic
Analyzes the document for common chapter headings, scene breaks, and italicized words and applies
the appropriate HTML markup during conversion.
Formatting style: Markdown
calibre also supports running TXT input though a transformation preprocessor known as Markdown.
Markdown allows for basic formatting to be added to TXT documents, such as bold, italics, section
headings, tables, lists, a Table of Contents, etc. Marking chapter headings with a leading # and setting
the chapter XPath detection expression to “//h:h1” is the easiest way to have a proper table of contents
generated from a TXT document. You can learn more about the Markdown syntax at daringreball
30
.
Formatting style: None
Applies no special formatting to the text, the document is converted to HTML with no other changes.
4.11.3 Convert PDF documents
PDF documents are one of the worst formats to convert from. They are a xed page size and text placement format.
Meaning, it is very dicult to determine where one paragraph ends and another begins. calibre will try to unwrap para-
graphs using a congurable, Line un-wrapping factor. This is a scale used to determine the length at which a line should
be unwrapped. Valid values are a decimal between 0 and 1. The default is 0.45, just under the median line length. Lower
this value to include more text in the unwrapping. Increase to include less. You can adjust this value in the conversion
settings under PDF Input.
Also, they often have headers and footers as part of the document that will become included with the text. Use the Search
and replace
panel to remove headers and footers to mitigate this issue. If the headers and footers are not removed from
the text it can throw o the paragraph unwrapping. To learn how to use the header and footer removal options, read All
about using regular expressions in calibre (page 215).
Some limitations of PDF input are:
Complex, multi-column, and image based documents are not supported.
Extraction of vector images and tables from within the document is also not supported.
Some PDFs use special glyphs to represent ll or or , etc. Conversion of these may or may not work depending
on just how they are represented internally in the PDF.
Links and Tables of Contents are not supported
PDFs that use embedded non-Unicode fonts to represent non-English characters will result in garbled output for
those characters
Some PDFs are made up of photographs of the page with OCRed text behind them. In such cases calibre uses the
OCRed text, which can be very dierent from what you see when you view the PDF le
PDFs that are used to display complex text, like right to left languages and math typesetting will not convert correctly
To re-iterate PDF is a really, really bad format to use as input. If you absolutely must use PDF, then be prepared for
an output ranging anywhere from decent to unusable, depending on the input PDF.
30
https://daringfireball.net/projects/markdown/syntax
4.11. Format specic tips 73
calibre User Manual, Release 7.19.0
4.11.4 Comic book collections
A comic book collection is a .cbc le. A .cbc le is a ZIP le that contains other CBZ/CBR les. In addition the .cbc le
must contain a simple text le called comics.txt, encoded in UTF-8. The comics.txt le must contain a list of the comics
les inside the .cbc le, in the form lename:title, as shown below:
one.cbz:Chapter One
two.cbz:Chapter Two
three.cbz:Chapter Three
The .cbc le will then contain:
comics.txt
one.cbz
two.cbz
three.cbz
calibre will automatically convert this .cbc le into a e-book with a Table of Contents pointing to each entry in comics.txt.
4.11.5 EPUB advanced formatting demo
Various advanced formatting for EPUB les is demonstrated in this demo le
31
. The le was created from hand coded
HTML using calibre and is meant to be used as a template for your own EPUB creation eorts.
The source HTML it was created from is available demo.zip
32
. The settings used to create the EPUB from the ZIP le
are:
ebook-convert demo.zip .epub -vv --authors "Kovid Goyal" --language en --level1-toc '/
,/*[@class="title"]' --disable-font-rescaling --page-breaks-before / --no-default-
,epub-cover
Note that because this le explores the potential of EPUB, most of the advanced formatting is not going to work on
readers less capable than calibre’s built-in EPUB viewer.
4.11.6 Convert ODT documents
calibre can directly convert ODT (OpenDocument Text) les. You should use styles to format your document and mini-
mize the use of direct formatting. When inserting images into your document you need to anchor them to the paragraph,
images anchored to a page will all end up in the front of the conversion.
To enable automatic detection of chapters, you need to mark them with the built-in styles called Heading 1, Heading 2,
…, Heading 6 (Heading 1 equates to the HTML tag <h1>, Heading 2 to <h2>, etc). When you convert in calibre you
can enter which style you used into the Detect chapters at box. Example:
If you mark Chapters with style Heading 2, you have to set the ‘Detect chapters at’ box to //h:h2
For a nested TOC with Sections marked with Heading 2 and the Chapters marked with Heading 3 you need to enter
//h:h2|//h:h3. On the Convert - TOC page set the Level 1 TOC box to //h:h2 and the Level 2 TOC box
to //h:h3.
Well-known document properties (Title, Keywords, Description, Creator) are recognized and calibre will use the rst
image (not to small, and with good aspect-ratio) as the cover image.
31
https://calibre-ebook.com/downloads/demos/demo.epub
32
https://calibre-ebook.com/downloads/demos/demo.zip
74 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
There is also an advanced property conversion mode, which is activated by setting the custom property opf.metadata
(‘Yes or No’ type) to Yes in your ODT document (File->Properties->Custom Properties). If this property is detected by
calibre, the following custom properties are recognized (opf.authors overrides document creator):
opf.titlesort
opf.authors
opf.authorsort
opf.publisher
opf.pubdate
opf.isbn
opf.language
opf.series
opf.seriesindex
In addition to this, you can specify the picture to use as the cover by naming it opf.cover (right click, Picture->Options-
>Name) in the ODT. If no picture with this name is found, the ‘smart’ method is used. As the cover detection might result
in double covers in certain output formats, the process will remove the paragraph (only if the only content is the cover!)
from the document. But this works only with the named picture!
To disable cover detection you can set the custom property opf.nocover (‘Yes or No’ type) to Yes in advanced mode.
4.11.7 Converting to PDF
The rst, most important, setting to decide on when converting to PDF is the page size. By default, calibre uses a page
size of “U.S. Letter”. You can change this to another standard page size or a completely custom size in the PDF Output
section of the conversion dialog. If you are generating a PDF to be used on a specic device, you can turn on the option
to use the page size from the output prole instead. So if your output prole is set to Kindle, calibre will create a PDF
with page size suitable for viewing on the small Kindle screen.
Headers and Footers
You can insert arbitrary headers and footers on each page of the PDF by specifying header and footer templates. Templates
are just snippets of HTML code that get rendered in the header and footer locations. For example, to display page numbers
centered at the bottom of every page, in green, use the following footer template:
<footer><div style="margin: auto; color: green">_PAGENUM_</div></footer>
calibre will automatically replace _PAGENUM_ with the current page number. You can even put dierent content on even
and odd pages, for example the following header template will show the title on odd pages and the author on even pages:
<header style="justify-content: flex-end">
<div class="even-page">_AUTHOR_</div>
<div class="odd-page"><i>_TITLE_</i></div>
</header>
calibre will automatically replace _TITLE_ and _AUTHOR_ with the title and author of the document being converted.
Setting justify-content to flex-end will cause the text to be right aligned.
You can also display text at the left and right edges and change the font size, as demonstrated with this header template:
<header style="justify-content: space-between; font-size: smaller">
<div>_TITLE_</div>
<div>_AUTHOR_</div>
</header>
4.11. Format specic tips 75
calibre User Manual, Release 7.19.0
This will display the title at the left and the author at the right, in a font size smaller than the main text.
You can also use the current section in templates, as shown below:
<header><div>_SECTION_</div></header>
_SECTION_ is replaced by whatever the name of the current section is. These names are taken from the metadata Table
of Contents in the document (the PDF Outline). If the document has no table of contents then it will be replaced by
empty text. If a single PDF page has multiple sections, the rst section on the page will be used. Similarly, there is a
variable named _TOP_LEVEL_SECTION_ that can be used to get the name of the current top-level section.
You can even use JavaScript inside the header and footer templates, for example, the following template will cause page
numbers to start at 4 instead of 1:
<footer>
<div></div>
<script>document.currentScript.parentNode.querySelector("div").innerHTML = "" + (_
,PAGENUM_ + 3)</script>
</footer>
In addition there are some more variables you can use in the headers and footers, documented below:
_TOTAL_PAGES_ - total number of pages in the PDF le, useful for implementing a progress counter, for exam-
ple.
_TOP_LEVEL_SECTION_PAGES_ - total number of pages in the current top level section
_TOP_LEVEL_SECTION_PAGENUM_ - the page number of the current page within the current top level section
® Note
When adding headers and footers make sure you set the page top and bottom margins to large enough values, under
the PDF Output section of the conversion dialog.
Printable Table of Contents
You can also insert a printable Table of Contents at the end of the PDF that lists the page numbers for every section. This
is very useful if you intend to print out the PDF to paper. If you wish to use the PDF on an electronic device, then the
PDF Outline provides this functionality and is generated by default.
You can customize the look of the generated Table of contents by using the Extra CSS conversion setting under the Look
& feel part of the conversion dialog. The default CSS used is listed below, simply copy it and make whatever changes you
like.
.calibre-pdf-toc table { width: 100%% }
.calibre-pdf-toc table tr td:last-of-type { text-align: right }
.calibre-pdf-toc .level-0 {
font-size: larger;
}
.calibre-pdf-toc .level-1 td:first-of-type { padding-left: 1.4em }
.calibre-pdf-toc .level-2 td:first-of-type { padding-left: 2.8em }
76 Chapter 4. E-book conversion
calibre User Manual, Release 7.19.0
Custom page margins for individual HTML les
If you are converting an EPUB or AZW3 le with multiple individual HTML les inside it and you want to change the
page margins for a particular HTML le you can add the following style block to the HTML le using the calibre E-book
editor:
<style>
@page {
margin-left: 10pt;
margin-right: 10pt;
margin-top: 10pt;
margin-bottom: 10pt;
}
</style>
Then, in the PDF output section of the conversion dialog, turn on the option to Use page margins from the document being
converted. Now all pages generated from this HTML le will have 10pt margins.
4.11. Format specic tips 77
calibre User Manual, Release 7.19.0
78 Chapter 4. E-book conversion
CHAPTER
FIVE
EDITING E-BOOKS
calibre has an integrated e-book editor that can be used to edit books in the EPUB and AZW3 (Kindle) formats. The
editor shows you the HTML and CSS that is used internally inside the book les, with a live preview that updates as you
make changes. It also contains various automated tools to perform common cleanup and xing tasks.
You can use this editor by right clicking on any book in calibre and selecting Edit book.
Contents
Basic workow (page 81)
The File browser (page 83)
Renaming les (page 84)
Merging les (page 84)
Changing text le order (page 85)
79
calibre User Manual, Release 7.19.0
Marking the cover (page 85)
Deleting les (page 85)
Exporting les (page 85)
Adding new images/fonts/etc. or creating new blank les (page 85)
Replacing les (page 86)
Linking stylesheets to HTML les eciently (page 86)
Search & replace (page 86)
Saved searches (page 86)
Function mode (page 87)
Search ignoring HTML tags (page 87)
Automated tools (page 87)
Editing the Table of Contents (page 87)
Checking the book (page 88)
Adding a cover (page 89)
Embedding referenced fonts (page 89)
Subsetting embedded fonts (page 89)
Smartening punctuation (page 90)
Transforming CSS properties (page 90)
Removing unused CSS rules (page 90)
Fixing HTML (page 90)
Beautifying les (page 90)
Inserting an inline Table of Contents (page 91)
Setting Semantics (page 91)
Filtering style information (page 91)
Upgrading the book’s internals (page 91)
Checkpoints (page 91)
The Live preview panel (page 93)
Splitting HTML les (page 94)
The Live CSS panel (page 95)
Miscellaneous tools (page 96)
The Table of Contents view (page 96)
Checking the spelling of words in the book (page 96)
Inserting special characters (page 98)
The code inspector view (page 99)
Checking external links (page 99)
80 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
Downloading external resources (page 99)
Arranging les into folders by type (page 99)
Importing les in other e-book formats as EPUB (page 99)
The Reports tool (page 110)
Special features in the code editor (page 110)
Syntax highlighting (page 110)
Context sensitive help (page 111)
Auto-complete (page 111)
Snippets (page 111)
5.1 Basic workow
® Note
A video tour of the calibre E-book editor is available here
33
.
When you rst open a book with the Edit book tool, you will be presented with a list of les on the left. These are the
individual HTML les, stylesheets, images, etc. that make up the content of the book. Simply double click on a le to
start editing it. Note that if you want to do anything more sophisticated than making a few small tweaks, you will need to
know HTML Tutorial
34
and CSS Tutorial
35
.
As you make changes to the HTML or CSS in the editor, the changes will be previewed, live, in the preview panel to the
right. When you are happy with how the changes you have made look, click the Save button or use File → Save to save
your changes into the e-book.
One useful feature is Checkpoints. Before you embark on some ambitious set of edits, you can create a checkpoint. The
checkpoint will preserve the current state of your book, then if in the future you decide you don’t like the changes you
have made to you can go back to the state when you created the checkpoint. To create a checkpoint, use Edit → Create
checkpoint. Checkpoints will also be automatically created for you whenever you run any automated tool like global search
and replace. The checkpointing functionality is in addition to the normal undo/redo mechanism when editing individual
les. Checkpoints are needed for when changes are spread over multiple les in the book.
That is the basic work ow for editing books Open a le, make changes, preview and save. The rest of this manual will
discuss the various tools and features present to allow you to perform specic tasks eciently.
33
https://calibre-ebook.com/demo#tutorials
34
http://html.net/tutorials/html/
35
http://html.net/tutorials/css/
5.1. Basic workow 81
calibre User Manual, Release 7.19.0
82 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.2 The File browser
5.2. The File browser 83
calibre User Manual, Release 7.19.0
The File browser gives you an overview of the various les inside the book you are editing. The les are arranged by
category, with text (HTML) les at the top, followed by stylesheet (CSS) les, images and so on. Simply double click on
a le to start editing it. Editing is supported for HTML, CSS and image les. The order of text les is the same order
that they would be displayed in, if you were reading the book. All other les are arranged alphabetically.
By hovering your mouse over an entry, you can see its size, and also, at the bottom of the screen, the full path to the le
inside the book. Note that les inside e-books are compressed, so the size of the nal book is not the sum of the individual
le sizes.
Many les have special meaning, in the book. These will typically have an icon next to their names, indicating the special
meaning. For example, in the picture to the left, you can see that the les cover_image.jpg and titlepage.xhtml have the
icon of a cover next to them, this indicates they are the book cover image and titlepage. Similarly, the content.opf le
has a metadata icon next to it, indicating the book metadata is present in it and the toc.ncx le has a T icon next to it,
indicating it is the Table of Contents.
You can perform many actions on individual les, by right clicking them.
5.2.1 Renaming les
You can rename an individual le by right clicking it and selecting Rename. Renaming a le automatically updates all
links and references to it throughout the book. So all you have to do is provide the new name, calibre will take care of
the rest.
You can also bulk rename many les at once. This is useful if you want the les to have some simple name pattern. For
example you might want to rename all the HTML les to have names Chapter-1.html, Chapter-2.html and so on. Select
the les you want bulk renamed by holding down the Shift or Ctrl key and clicking the les. Then right click and
select Bulk rename. Enter a prex and what number you would like the automatic numbering to start at, click OK and
you are done. The bulk rename dialog also lets you rename les by the order they appear in the book instead of the order
you selected them in, useful, for instance to rename all images by the order they appear.
Finally, you can bulk change the le extension for all selected les. Select multiple les, as above, and right click and
choose Change the le extension for the selected les.
5.2.2 Merging les
Sometimes, you may want to merge two HTML les or two CSS les together. It can sometimes be useful to have
everything in a single le. Be wary, though, putting a lot of content into a single le will cause performance problems
when viewing the book in a typical e-book reader.
To merge multiple les together, select them by holding the Ctrl key and clicking on them (make sure you only select
les of one type, either all HTML les or all CSS les and so on). Then right click and select merge. That’s all, calibre
will merge the les, automatically taking care of migrating all links and references to the merged les. Note that merging
les can sometimes cause text styling to change, since the individual les could have used dierent stylesheets.
You can also select text les and then drag and drop the text les onto another text le to merge the dropped text les into
the target text le.
84 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.2.3 Changing text le order
You can re-arrange the order in which text (HTML) les are opened when reading the book by simply dragging and
dropping them in the File browser or clicking on the le to move and then pressing the Ctrl+Shift modiers with the
Up
,
Down
,
Home
or
End
keys. For the technically inclined, this is called re-ordering the book spine.
Note that you have to drop the items between other items, not on top of them, this can be a little ddly until you get used
to it. Dropping on top of another le will cause the les to be merged.
5.2.4 Marking the cover
E-books typically have a cover image. This image is indicated in the File browser by the icon of a brown book next to
the image name. If you want to designate some other image as the cover, you can do so by right clicking on the le and
choosing Mark as cover.
In addition, EPUB les has the concept of a titlepage. A title page is a HTML le that acts as the title page/cover for the
book. You can mark an HTML le as the titlepage when editing EPUBs by right-clicking. Be careful that the le you
mark contains only the cover information. If it contains other content, such as the rst chapter, then that content will be
lost if the user ever converts the EPUB le in calibre to another format. This is because when converting, calibre assumes
that the marked title page contains only the cover and no other content.
5.2.5 Deleting les
You can delete les by either right clicking on them or by selecting them and pressing the Delete key. Deleting a le
removes all references to the le from the OPF le, saving you that chore. However, references in other places are not
removed, you can use the Check Book tool to easily nd and remove/replace them.
5.2.6 Exporting les
You can export a le from inside the book to somewhere else on your computer. This is useful if you want to work on
the le in isolation, with specialised tools. To do this, simply right click on the le and choose Export.
Once you are done working on the exported le, you can re-import it into the book, by right clicking on the le again and
choosing Replace with le… which will allow you to replace the le in the book with the previously exported le.
You can also copy les between multiple editor instances. Select the les you want to copy in the File browser, then right
click and choose, Copy selected les to another editor instance. Then, in the other editor instance, right click in the File
browser and choose Paste le from other editor instance.
5.2.7 Adding new images/fonts/etc. or creating new blank les
You can add a new image, font, stylesheet, etc. from your computer into the book by clicking File → New le. This lets
you either import a le by clicking the Import resource le button or create a new blank HTML le or stylesheet by simply
entering the le name into the box for the new le.
You can also import multiple les into the book at once using File->Import les into book.
5.2. The File browser 85
calibre User Manual, Release 7.19.0
5.2.8 Replacing les
You can easily replace existing les in the book, by right clicking on the le and choosing replace. This will automatically
update all links and references, in case the replacement le has a dierent name than the le being replaced.
5.2.9 Linking stylesheets to HTML les eciently
As a convenience, you can select multiple HTML les in the File browser, right click and choose Link stylesheets to have
calibre automatically insert the <link> tags for those stylesheets into all the selected HTML les.
5.3 Search & replace
Edit book has a very powerful search and replace interface that allows you to search and replace text in the current le,
across all les and even in a marked region of the current le. You can search using a normal search or using regular
expressions. To learn how to use regular expressions for advanced searching, see All about using regular expressions in
calibre (page 215).
Start the search and replace via the Search → Find/replace menu entry (you must be editing an HTML or CSS le).
Type the text you want to nd into the Find box and its replacement into the Replace box. You can the click the appropriate
buttons to Find the next match, replace the current match and replace all matches.
Using the drop downs at the bottom of the box, you can have the search operate over the current le, all text les, all style
les or all les. You can also choose the search mode to be a normal (string) search or a regular expression search.
You can count all the matches for a search expression via Search → Count all. The count will run over whatever les/regions
you have selected in the dropdown box.
You can also go to a specic line in the currently open editor via Search → Go to line.
® Note
Remember, to harness the full power of search and replace, you will need to use regular expressions. See All about
using regular expressions in calibre (page 215).
5.3.1 Saved searches
You can save frequently used search/replace expressions (including function mode expressions) and reuse them multiple
times. To save a search simply right click in the Find box and select Save current search.
You can bring up the saved searches via Search → Saved searches. This will present you with a list of search and replace
expressions that you can apply. You can even select multiple entries in the list by holding down the Ctrl key while
clicking so as to run multiple search and replace expressions in a single operation.
86 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.3.2 Function mode
Function mode allows you to write arbitrarily powerful Python functions that are run on every Find/replace. You can do
pretty much any text manipulation you like in function mode. For more information, see Function mode for Search &
replace in the Editor (page 99).
5.3.3 Search ignoring HTML tags
There is also a dedicated tool for searching for text, ignoring any HTML tags in between. For example, if the book has
the HTML Empahisis on a <i>word</i>. you can search for on a word and it will be found even though
there is an <i> tag in the middle. Use this tool via the Search → Search ignoring HTML markup menu item.
5.4 Automated tools
Edit book has various tools to help with common tasks. These are accessed via the Tools menu.
5.4.1 Editing the Table of Contents
There is a dedicated tool to ease editing of the Table of Contents. Launch it with Tools → Table of Contents → Edit Table
of Contents.
5.4. Automated tools 87
calibre User Manual, Release 7.19.0
The Edit Table of Contents tool shows you the current Table of Contents (if any) on the left. Simply double click on any
entry to change its text. You can also re-arrange entries by drag and drop or by using the buttons to the right.
For books that do not have a pre-existing Table of Contents, the tool gives you various options to auto-generate a Table
of Contents from the text. You can generate from the headings in the document, from links, from individual les and so
on.
You can edit individual entries by clicking on them and then clicking the Change the location this entry points to button.
This will open up a mini-preview of the book, simply move the mouse cursor over the book view panel, and click where
you want the entry to point to. A thick green line will show you the location. Click OK once you are happy with the
location.
5.4.2 Checking the book
The Check book tool searches your book for problems that could prevent it working as intended on actual reader devices.
Activate it via Tools → Check book.
88 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
Any problems found are reported in a nice, easy to use list. Clicking any entry in the list shows you some help about that
error as well as giving you the option to auto-x that error, if the error can be xed automatically. You can also double
click the error to open the location of the error in an editor, so you can x it yourself.
Some of the checks performed are:
Malformed HTML markup. Any HTML markup that does not parse as well-formed XML is reported. Correcting it
will ensure that your markup works as intended in all contexts. calibre can also auto-x these errors, but auto-xing
can sometimes have unexpected eects, so use with care. As always, a checkpoint is created before auto-xing so
you can easily revert all changes. Auto-xing works by parsing the markup using the HTML5 algorithm, which is
highly fault tolerant and then converting to well formed XML.
Malformed or unknown CSS styles. Any CSS that is not valid or that has properties not dened in the CSS 2.1
standard (plus a few from CSS 3) are reported. CSS is checked in all stylesheets, inline style attributes and <style>
tags in HTML les.
Broken links. Links that point to les inside the book that are missing are reported.
Unreferenced les. Files in the book that are not referenced by any other le or are not in the spine are reported.
Various common problems in OPF les such as duplicate spine or manifest items, broken idrefs or meta cover tags,
missing required sections and so on.
Various compatibility checks for known problems that can cause the book to malfunction on reader devices.
5.4.3 Adding a cover
You can easily add a cover to the book via Tools → Add cover. This allows you to either choose an existing image in the
book as the cover or import a new image into the book and make it the cover. When editing EPUB les, the HTML
wrapper for the cover is automatically generated. If an existing cover in the book is found, it is replaced. The tool also
automatically takes care of correctly marking the cover les as covers in the OPF.
5.4.4 Embedding referenced fonts
Accessed via Tools → Embed reference fonts, this tool nds all fonts referenced in the book and if they are not already
embedded, searches your computer for them and embeds them into the book, if found. Please make sure that you have
the necessary copyrights for embedding commercially licensed fonts, before doing this.
5.4.5 Subsetting embedded fonts
Accessed via Tools → Subset embedded fonts, this tool reduces all the fonts in the book to only contain glyphs for the text
actually present in the book. This commonly reduces the size of the font les by ~ 50%. However, be aware that once the
fonts are subset, if you add new text whose characters are not previously present in the subset font, the font will not work
for the new text. So do this only as the last step in your workow.
5.4. Automated tools 89
calibre User Manual, Release 7.19.0
5.4.6 Smartening punctuation
Convert plain text dashes, ellipsis, quotes, multiple hyphens, etc. into their typographically correct equivalents. Note
that the algorithm can sometimes generate incorrect results, especially when single quotes at the start of contractions are
involved. Accessed via
Tools → Smarten punctuation
.
5.4.7 Transforming CSS properties
Create rules to transform the styling of the book. For example, create a rule to convert all red text to green or to double
the font size of all text in the book or make text of a certain font family italic, etc.
Creating the rules is simple, the rules follow a natural language format, that looks like:
If the property color is red change it to green
If the property font-size is any value multiply the value by 2
Accessed via Tools → Transform styles.
5.4.8 Removing unused CSS rules
Remove all unused CSS rules from stylesheets and <style> tags. Some books created from production templates can have
a large number of extra CSS rules that don’t match any actual content. These extra rules can slow down readers that need
to process them all. Accessed via Tools → Remove unused CSS.
5.4.9 Fixing HTML
This tool simply converts HTML that cannot be parsed as XML into well-formed XML. It is very common in e-books to
have non-well-formed XML, so this tool simply automates the process of xing such HTML. The tool works by parsing
the HTML using the HTML5 algorithm (the algorithm used in all modern browsers) and then converting the result into
XML. Be aware that auto-xing can sometimes have counter-intuitive results. If you prefer, you can use the Check Book
tool discussed above to nd and manually correct problems in the HTML. Accessed via Tools → Fix HTML.
5.4.10 Beautifying les
This tool is used to auto-format all HTML and CSS les so that they “look pretty”. The code is auto-indented so that
it lines up nicely, blank lines are inserted where appropriate and so on. Note that beautifying also auto-xes broken
HTML/CSS. Therefore, if you don’t want any auto-xing to be performed, rst use the Check Book tool to correct all
problems and only then run beautify. Accessed via Tools → Beautify all les.
® Note
In HTML any text can have signicant whitespace, via the CSS white-space directive. Therefore, beautication could
potentially change the rendering of the HTML. To avoid this as far as possible, the beautify algorithm only beauties
block level tags that contain other block level tags. So, for example, text inside a <p> tag will not have its whitespace
changed. But a <body> tag that contains only other <p> and <div> tags will be beautied. This can sometimes mean
that a particular le will not be aected by beautify as it has no suitable block level tags. In such cases you can try
dierent beautication tools, that are less careful, for example: HTML Tidy
36
.
36
https://infohound.net/tidy/
90 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.4.11 Inserting an inline Table of Contents
Normally in e-books, the Table of Contents is separate from the main text and is typically accessed via a special Table of
Contents button/menu in the e-book reading device. You can also have calibre automatically generate an inline Table of
Contents that becomes part of the text of the book. It is generated based on the currently dened Table of Contents.
If you use this tool multiple times, each invocation will cause the previously created inline Table of Contents to be replaced.
The tool can be accessed via Tools → Table of Contents → Insert inline Table of Contents.
5.4.12 Setting Semantics
This tool is used to set semantics in EPUB les. Semantics are simply, links in the OPF le that identify certain locations
in the book as having special meaning. You can use them to identify the foreword, dedication, cover, table of contents,
etc. Simply choose the type of semantic information you want to specify and then select the location in the book the link
should point to. This tool can be accessed via Tools → Set semantics.
5.4.13 Filtering style information
This tool can be used to easily remove specied CSS style properties from the entire book. You can tell it what properties
you want removed, for example, color, background-color, line-height and it will remove them from
everywhere they occur stylesheets, <style> tags and inline style attributes. After removing the style information,
a summary of all the changes made is displayed so you can see exactly what was changed. The tool can be accessed via
Tools → Filter style information.
5.4.14 Upgrading the book’s internals
This tool can be used to upgrade the book’s internals, if possible. For instance it will upgrade EPUB 2 books to EPUB 3
books. The tool can be accessed via Upgrade book internals.
5.5 Checkpoints
Checkpoints are a way to mark the current state of the book as “special”. You can then go on to do whatever changes you
want to the book and if you don’t like the results, return to the checkpointed state. Checkpoints are automatically created
every time you run any of the automated tools described in the previous section.
You can create a checkpoint via Edit → Create checkpoint. And go back to a previous checkpoint with Edit → Revert to
The check pointing functionality is in addition to the normal Undo/redo mechanism when editing individual les. Check-
points are needed for when changes are spread over multiple les in the book or when you wish to be able to revert a large
group of related changes as a whole.
You can see a list of available checkpoints via View → Checkpoints. You can compare the current state of the book to a
specied checkpoint using the Comparing e-books (page 121) tool by selecting the checkpoint of interest and clicking
the Compare button. The Revert to button restores the book to the selected checkpoint, undoing all changes since that
checkpoint was created.
5.5. Checkpoints 91
calibre User Manual, Release 7.19.0
92 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.6 The Live preview panel
5.6. The Live preview panel 93
calibre User Manual, Release 7.19.0
The File preview gives you an overview of the various les inside The live preview panel shows you the changes you are
making live (with a second or two of delay). As you edit HTML or CSS les, the preview panel is updated automatically
to reect your changes. As you move the cursor around in the editor, the preview panel will track its location, showing you
the corresponding location in the book. Clicking in the preview panel, will cause the cursor in the editor to be positioned
over the element you clicked. If you click a link pointing to another le in the book, that le will be opened in the edit
and the preview panel, automatically.
You can turn o the automatic syncing of position and live preview of changes by buttons under the preview panel. The
live update of the preview panel only happens when you are not actively typing in the editor, so as not to be distracting or
slow you down, waiting for the preview to render.
The preview panel shows you how the text will look when viewed. However, the preview panel is not a substitute for
actually testing your book an actual reader device. It is both more, and less capable than an actual reader. It will tolerate
errors and sloppy markup much better than most reader devices. It will also not show you page margins, page breaks and
embedded fonts that use font name aliasing. Use the preview panel while you are working on the book, but once you are
done, review it in an actual reader device or software emulator.
® Note
The preview panel does not support embedded fonts if the name of the font inside the font le does not match the
name in the CSS @font-face rule. You can use the Check Book tool to quickly nd and x any such problem fonts.
5.6.1 Splitting HTML les
One, perhaps non-obvious, use of the preview panel is to split long HTML les. While viewing the le you want to split,
click the Split mode button under the preview panel . Then simply move your mouse to the place where you want
to split the le and click. A thick green line will show you exactly where the split will happen as you move your mouse.
Once you have found the location you want, simply click and the split will be performed.
Splitting the le will automatically update all links and references that pointed into the bottom half of the le and will
open the newly split le in an editor.
You can also split a single HTML le at multiple locations automatically, by right clicking inside the le in the editor and
choosing Split at multiple locations. This will allow you to easily split a large le at all heading tags or all tags having a
certain class and so on.
94 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.7 The Live CSS panel
The
Live CSS
panel shows you all the style rules that apply to the tag you are currently editing. The name of tag, along
with its line number in the editor are displayed, followed by a list of matching style rules.
It is a great way to quickly see which style rules apply to any tag. The view also has clickable links (in blue), which take
you directly to the location where the style was dened, in case you wish to make any changes to the style rules. Style
rules that apply directly to the tag, as well as rules that are inherited from parent tags are shown.
The panel also shows you what the nally calculated styles for the tag are. Properties in the list that are superseded by
higher priority rules are shown with a line through them.
You can enable the Live CSS panel via View → Live CSS.
5.7. The Live CSS panel 95
calibre User Manual, Release 7.19.0
5.8 Miscellaneous tools
There are a few more tools that can be useful while you edit the book.
5.8.1 The Table of Contents view
The Table of Contents view shows you the current table of contents in the book. Double clicking on any entry opens the
place that entry points to in an editor. You can right click to edit the Table of Contents, refresh the view or expand/collapse
all items. Access this view via View → Table of Contents.
5.8.2 Checking the spelling of words in the book
You can run a spelling checker via Tools → Check spelling.
96 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
Words are shown with the number of times they occur in the book and the language the word belongs to. Language
information is taken from the books metadata and from lang attributes in the HTML les. This allows the spell checker
to work well even with books that contain text in multiple languages. For example, in the following HTML extract, the
word color will be checked using American English and the word colour using British English:
<div lang="en_US">color <span lang="en_GB">colour</span></div>
® Note
You can double click a word to highlight the next occurrence of that word in the editor. This is useful if you wish to
manually edit the word, or see what context it is in.
To change a word, simply double click one of the suggested alternative spellings on the right, or type in your own corrected
5.8. Miscellaneous tools 97
calibre User Manual, Release 7.19.0
spelling and click the Change selected word to button. This will replace all occurrences of the word in the book. You can
also right click on a word in the main word list to change the word conveniently from the right click menu.
You can have the spelling checker ignore a word for the current session by clicking the Ignore button. You can also
add a word to the user dictionary by clicking the Add to dictionary button. The spelling checker supports multiple user
dictionaries, so you can select the dictionary you want the word added to.
You can also have the spelling checker display all the words in your book, not just the incorrectly spelled ones. This is
useful to see what words are most common in your book and to run a simple search and replace on individual words.
® Note
If you make any changes to the book by editing les while the spell check tool is open, you should click the Refresh
button in the Spell check tool. If you do not do this and continue to use the Spell check tool, you could lose the
changes you have made in the editor.
® Note
To exclude an individual le from being spell checked when running the spell check tool, you can use the Exclude les
button or add the following comment just under the opening tag in the le:
<!-- calibre-no-spell-check -->
Adding new dictionaries
The spelling checker comes with builtin dictionaries for the English and Spanish languages. You can install your own
dictionaries via Preferences → Editor → Manage spelling dictionaries. The spell checker can use dictionaries from the
LibreOce program (in the .oxt format). You can download these dictionaries from The LibreOce Extensions repos-
itory
37
.
5.8.3 Inserting special characters
You can insert characters that are dicult to type by using the Edit → Insert special character tool. This shows you all
Unicode characters, simply click on the character you want to type. If you hold Ctrl while clicking, the window will
close itself after inserting the selected character. This tool can be used to insert special characters into the main text or
into any other area of the user interface, such as the Search and replace tool.
Because there are a lot of characters, you can dene your own Favorite characters, that will be shown rst. Simply right
click on a character to mark it as favorite. You can also right click on a character in favorites to remove it from favorites.
Finally, you can re-arrange the order of characters in favorites by clicking the Re-arrange favorites button and then drag
and dropping the characters in favorites around.
You can also directly type in special characters using the keyboard. To do this, you type the Unicode code for the character
(in hexadecimal) and then press the Alt+X key which will convert the previously typed code into the corresponding
character. For example, to type ÿ you would type and then Alt+X. To type a non-breaking space you would use a0
and then Alt+X, to type the horizontal ellipsis you would use 2026 and Alt+X and so on.
Finally, you can type in special characters by using HTML named entities. For example, typing &nbsp; will be replaced
by a non breaking space when you type the semi-colon. The replacement happens only when typing the semi-colon.
37
https://extensions.libreoffice.org/?Tags%5B%5D=50
98 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.8.4 The code inspector view
This view shows you the HTML coding and CSS that applies to the current element of interest. You open it by right
clicking a location in the preview panel and choosing Inspect. It allows you to see the HTML coding for that element
and more importantly, the CSS styles that apply to it. You can even dynamically edit the styles and see what eect your
changes have instantly. Note that editing the styles does not actually make changes to the book contents, it only allows
for quick experimentation. The ability to live edit inside the Inspector is under development.
5.8.5 Checking external links
You can use this tool to check all links in your book that point to external websites. The tool will try to visit every
externally linked website, and if the visit fails, it will report all broken links in a convenient format for you to x.
5.8.6 Downloading external resources
You can use this tool to automatically download any images/stylesheets/etc. in the book that are not bundled with the
book (i.e. they have URLs pointing to a location on the internet). The tool will nd all such resources and automatically
download them, add them to the book and replace all references to them to use the downloaded les.
5.8.7 Arranging les into folders by type
Often when editing EPUB les that you get from somewhere, you will nd that the les inside the EPUB are arranged
haphazardly, in dierent sub-folders. This tool allows you to automatically move all les into sub-folders based on their
types. Access it via Tools → Arrange into folders. Note that this tool only changes how the les are arranged inside the
EPUB, it does not change how they are displayed in the File browser.
5.8.8 Importing les in other e-book formats as EPUB
The editor includes the ability to import les in some other e-book formats directly as a new EPUB, without going through
a full conversion. This is particularly useful to directly create EPUB les from your own hand-edited HTML les. You
can do this via File → Import an HTML or DOCX le as a new book.
Function mode for Search & replace in the Editor
The Search & replace tool in the editor support a function mode. In this mode, you can combine regular expressions
(see All about using regular expressions in calibre (page 215)) with arbitrarily powerful Python functions to do all sorts of
advanced text processing.
In the standard regexp mode for search and replace, you specify both a regular expression to search for as well as a template
that is used to replace all found matches. In function mode, instead of using a xed template, you specify an arbitrary
function, in the Python programming language
38
. This allows you to do lots of things that are not possible with simple
templates.
Techniques for using function mode and the syntax will be described by means of examples, showing you how to create
functions to perform progressively more complex tasks.
38
https://docs.python.org
5.8. Miscellaneous tools 99
calibre User Manual, Release 7.19.0
Automatically xing the case of headings in the document
Here, we will leverage one of the builtin functions in the editor to automatically change the case of all text inside heading
tags to title case:
Find expression: <([Hh][1-6])[^>]*>.+?</\1>
For the function, simply choose the Title-case text (ignore tags) builtin function. The will change titles that look like:
<h1>some TITLE</h1> to <h1>Some Title</h1>. It will work even if there are other HTML tags inside the
heading tags.
Your rst custom function - smartening hyphens
The real power of function mode comes from being able to create your own functions to process text in arbitrary ways.
The Smarten Punctuation tool in the editor leaves individual hyphens alone, so you can use the this function to replace
them with em-dashes.
To create a new function, simply click the Create/edit button to create a new function and copy the Python code from
below.
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
return match.group().replace('--', '—').replace('-', '—')
Every Search & replace custom function must have a unique name and consist of a Python function named replace,
that accepts all the arguments shown above. For the moment, we won’t worry about all the dierent arguments to re-
place() function. Just focus on the match argument. It represents a match when running a search and replace. Its
full documentation in available here
39
. match.group() simply returns all the matched text and all we do is replace
hyphens in that text with em-dashes, rst replacing double hyphens and then single hyphens.
Use this function with the nd regular expression:
>[^<>]+<
And it will replace all hyphens with em-dashes, but only in actual text and not inside HTML tag denitions.
39
https://docs.python.org/library/re.html#match-objects
100 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
The power of function mode - using a spelling dictionary to x mis-hyphenated words
Often, e-books created from scans of printed books contain mis-hyphenated words words that were split at the end of
the line on the printed page. We will write a simple function to automatically nd and x such words.
import regex
from calibre import replace_entities
from calibre import prepare_string_for_xml
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
def replace_word(wmatch):
# Try to remove the hyphen and replace the words if the resulting
# hyphen free word is recognized by the dictionary
without_hyphen = wmatch.group(1) + wmatch.group(2)
if dictionaries.recognized(without_hyphen):
return without_hyphen
return wmatch.group()
# Search for words split by a hyphen
text = replace_entities(match.group()[1:-1]) # Handle HTML entities like &amp;
corrected = regex.sub(r'(\w+)\s*-\s*(\w+)', replace_word, text, flags=regex.
,VERSION1 | regex.UNICODE)
return '>%s<' % prepare_string_for_xml(corrected) # Put back required entities
Use this function with the same nd expression as before, namely:
>[^<>]+<
And it will magically x all mis-hyphenated words in the text of the book. The main trick is to use one of the useful extra
arguments to the replace function, dictionaries. This refers to the dictionaries the editor itself uses to spell check
text in the book. What this function does is look for words separated by a hyphen, remove the hyphen and check if the
dictionary recognizes the composite word, if it does, the original words are replaced by the hyphen free composite word.
Note that one limitation of this technique is it will only work for mono-lingual books, because, by default,
dictionaries.recognized() uses the main language of the book.
Auto numbering sections
Now we will see something a little dierent. Suppose your HTML le has many sections, each with a heading in an <h2>
tag that looks like <h2>Some text</h2>. You can create a custom function that will automatically number these
headings with consecutive section numbers, so that they look like <h2>1. Some text</h2>.
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
section_number = '%d. ' % number
return match.group(1) + section_number + match.group(2)
# Ensure that when running over multiple files, the files are processed
# in the order in which they appear in the book
replace.file_order = 'spine'
Use it with the nd expression:
5.8. Miscellaneous tools 101
calibre User Manual, Release 7.19.0
(?s)(<h2[^<>]*>)(.+?</h2>)
Place the cursor at the top of the le and click Replace all.
This function uses another of the useful extra arguments to replace(): the number argument. When doing a Replace
All number is automatically incremented for every successive match.
Another new feature is the use of replace.file_order setting that to 'spine' means that if this search is run
on multiple HTML les, the les are processed in the order in which they appear in the book. See Choose le order when
running on multiple HTML les (page 105) for details.
Auto create a Table of Contents
Finally, lets try something a little more ambitious. Suppose your book has headings in h1 and h2 tags that look like <h1
id="someid">Some Text</h1>. We will auto-generate an HTML Table of Contents based on these headings.
Create the custom function below:
from calibre import replace_entities
from calibre.ebooks.oeb.polish.toc import TOC, toc_to_html
from calibre.gui2.tweak_book import current_container
from calibre.ebooks.oeb.base import xml2str
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
if match is None:
# All matches found, output the resulting Table of Contents.
# The argument metadata is the metadata of the book being edited
if 'toc' in data:
toc = data['toc']
root = TOC()
for (file_name, tag_name, anchor, text) in toc:
parent = root.children[-1] if tag_name == 'h2' and root.children else
,root
parent.add(text, file_name, anchor)
toc = toc_to_html(root, current_container(), 'toc.html', 'Table of
,Contents for ' + metadata.title, metadata.language)
print(xml2str(toc))
else:
print('No headings to build ToC from found')
else:
# Add an entry corresponding to this match to the Table of Contents
if 'toc' not in data:
# The entries are stored in the data object, which will persist
# for all invocations of this function during a 'Replace All' operation
data['toc'] = []
tag_name, anchor, text = match.group(1), replace_entities(match.group(2)),
,replace_entities(match.group(3))
data['toc'].append((file_name, tag_name, anchor, text))
return match.group() # We don't want to make any actual changes, so return
,the original matched text
# Ensure that we are called once after the last match is found so we can
# output the ToC
replace.call_after_last_match = True
# Ensure that when running over multiple files, this function is called,
(continues on next page)
102 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
(continued from previous page)
# the files are processed in the order in which they appear in the book
replace.file_order = 'spine'
And use it with the nd expression:
<(h[12]) [^<>]* id=['"]([^'"]+)['"][^<>]*>([^<>]+)
Run the search on All text les and at the end of the search, a window will popup with “Debug output from your function”
which will have the HTML Table of Contents, ready to be pasted into toc.html.
The function above is heavily commented, so it should be easy to follow. The key new feature is the use of another useful
extra argument to the replace() function, the data object. The data object is a Python dictionary that persists
between all successive invocations of replace() during a single Replace All operation.
Another new feature is the use of call_after_last_match setting that to True on the replace() function
means that the editor will call replace() one extra time after all matches have been found. For this extra call, the
match object will be None.
This was just a demonstration to show you the power of function mode, if you really needed to generate a Table of
Contents from headings in your book, you would be better o using the dedicated Table of Contents tool in Tools → Table
of Contents.
The API for the function mode
All function mode functions must be Python functions named replace, with the following signature:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
return a_string
When a nd/replace is run, for every match that is found, the replace() function will be called, it must return the
replacement string for that match. If no replacements are to be done, it should return match.group() which is the
original string. The various arguments to the replace() function are documented below.
The match argument
The match argument represents the currently found match. It is a Python Match object
40
. Its most useful method is
group() which can be used to get the matched text corresponding to individual capture groups in the search regular
expression.
The number argument
The number argument is the number of the current match. When you run Replace All, every successive match will cause
replace() to be called with an increasing number. The rst match has number 1.
40
https://docs.python.org/library/re.html#match-objects
5.8. Miscellaneous tools 103
calibre User Manual, Release 7.19.0
The file_name argument
This is the lename of the le in which the current match was found. When searching inside marked text, the file_name
is empty. The file_name is in canonical form, a path relative to the root of the book, using / as the path separator.
The metadata argument
This represents the metadata of the current book, such as title, authors, language, etc. It is an object of class calibre.
ebooks.metadata.book.base.Metadata (page 211). Useful attributes include, title, authors (a list of
authors) and language (the language code).
The dictionaries argument
This represents the collection of dictionaries used for spell checking the current book. Its most useful method is
dictionaries.recognized(word) which will return True if the passed in word is recognized by the dictionary
for the current book’s language.
The data argument
This a simple Python dictionary. When you run Replace all, every successive match will cause replace() to
be called with the same dictionary as data. You can thus use it to store arbitrary data between invocations of
replace() during a Replace all operation.
The functions argument
The functions argument gives you access to all other user dened functions. This is useful for code re-use. You
can dene utility functions in one place and re-use them in all your other functions. For example, suppose you create a
function name My Function like this:
def utility():
# do something
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
...
Then, in another function, you can access the utility() function like this:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
utility = functions['My Function']['utility']
...
You can also use the functions object to store persistent data, that can be re-used by other functions. For example, you
could have one function that when run with Replace All collects some data and another function that uses it when it is run
afterwards. Consider the following two functions:
# Function One
persistent_data = {}
(continues on next page)
104 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
(continued from previous page)
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
...
persistent_data['something'] = 'some data'
# Function Two
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
persistent_data = functions['Function One']['persistent_data']
...
Debugging your functions
You can debug the functions you create by using the standard print() function from Python. The output of print will
be displayed in a popup window after the Find/replace has completed. You saw an example of using print() to output
an entire table of contents above.
Choose le order when running on multiple HTML les
When you run a Replace all on multiple HTML les, the order in which the les are processes depends on what les
you have open for editing. You can force the search to process les in the order in which the appear by setting the
file_order attribute on your function, like this:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
...
replace.file_order = 'spine'
file_order accepts two values, spine and spine-reverse which cause the search to process multiple les in
the order they appear in the book, either forwards or backwards, respectively.
Having your function called an extra time after the last match is found
Sometimes, as in the auto generate table of contents example above, it is useful to have your function called an extra time
after the last match is found. You can do this by setting the call_after_last_match attribute on your function,
like this:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
...
replace.call_after_last_match = True
5.8. Miscellaneous tools 105
calibre User Manual, Release 7.19.0
Appending the output from the function to marked text
When running search and replace on marked text, it is sometimes useful to append so text to the end of the marked text.
You can do that by setting the append_final_output_to_marked attribute on your function (note that you also
need to set call_after_last_match), like this:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
...
return 'some text to append'
replace.call_after_last_match = True
replace.append_final_output_to_marked = True
Suppressing the result dialog when performing searches on marked text
You can also suppress the result dialog (which can slow down the repeated application of a search/replace on many blocks
of text) by setting the suppress_result_dialog attribute on your function, like this:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
,**kwargs):
...
replace.suppress_result_dialog = True
More examples
More useful examples, contributed by calibre users, can be found in the calibre E-book editor forum
41
.
Snippets
The calibre E-book editor supports snippets. A snippet is a piece of text that is either re-used often or contains a lot of
redundant text. The editor allows you to insert a snippet with only a few key strokes. For example, suppose you often nd
yourself inserting link tags when editing HTML les, then you can simply type <a in the editor and press Control+J.
The editor will expand it to:
<a href="filename"></a>
Not only that, the word filename will be selected, with the cursor placed over it, so that you can easily type in the
real lename, using the editor’s nifty Auto-complete (page 111) feature. And once you are done typing the lename, press
Control+J again and the cursor will jump to the position in between the <a> tags so you can easily type in the text
for the link.
The snippets system in the editor is very sophisticated, there are a few built-in snippets and you can create your own to
suit your editing style.
The following discussion of the built-in snippets should help illustrate the power of the snippets system.
41
https://www.mobileread.com/forums/showthread.php?t=237181
106 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
® Note
You can also use snippets in the text entry elds in the Search & replace panel, however, placeholders (using Con-
trol+J to jump around) will not work.
The built-in snippets
The built-in snippets are described below. Note that you can override them by creating your own snippets with the same
trigger text.
Inserting ller text [Lorem]
The rst built-in snippet, and the simplest is used to insert ller text into a document. The ller text is taken from De
nibus bonorum et malorum
42
a philosophical work by Cicero (translated to English). To use it simply type Lorem in
an HTML le and press Control+J. It will be replaced by a couple of paragraphs of ller.
The denition of this snippet is very simple, the trigger text is dened as Lorem and the template is dened simply as
the literal text to be inserted. You can easily customize it to use your favorite form of ller text.
Inserting a self-closing HTML tag [<>]
Now let’s look at a simple example of the powerful concept of placeholders. Say you want to insert the self-closing tag
<hr/>. Just type <>, and press Control+J, the editor will expand the snippet to:
<|/>
Here, the | symbol represents the current cursor position. You can then type hr and press Control+J to move the
cursor to after the end of the tag. This snippet is dened as:
Trigger: <>
Template: <$1/>$2
Placeholders are simply the dollar ($) sign followed by a number. When the snippet is expanded by pressing Control+J
the cursor is positioned at the rst placeholder (the placeholder with the lowest number). When you press Control+J
again the cursor jumps to the next placeholder (the placeholder with the next higher number).
Inserting an HTML link tag [<a]
HTML link tags all share a common structure. They have an href attribute and some text between the opening and
closing tags. A snippet to make typing them more ecient will introduce us to some more features of placeholders. To
use this snippet, simply type <a and press Control+J. The editor will expand this to:
<a href="filename|"></a>
Not only that, the word filename will be selected, with the cursor placed over it, so that you can easily type in the
real lename, using the editor’s nifty Auto-complete (page 111) feature. And once you are done typing the lename, press
Control+J again and the cursor will jump to the position in between the <a> tags so you can easily type in the text
42
https://en.wikipedia.org/wiki/De_finibus_bonorum_et_malorum
5.8. Miscellaneous tools 107
calibre User Manual, Release 7.19.0
for the link. After you are done typing the text, press Control+J again to jump to the point after the closing tag. This
snippet is dened as:
Trigger: <a
Template: <a href="${1:filename}">${2*}</a>$3
There are a couple of new features here. First the $1 placeholder has become more complex. It now includes some default
text
(the word
filename
). If a placeholder contains default text, the default text is substituted for the placeholder when
the snippet is expanded. Also when you jump to a placeholder with default text using Control+J, the default text is
selected. In this way, you can use default text to act as a reminder to you to ll in important parts of the template. You
can specify default text for a placeholder by using the syntax: ${<number>:default text}.
The other new feature is that the second placeholder has an asterisk after it (${2*}). This means that any text that was
selected before expanding the template is substituted for the placeholder. To see this in action, select some text in the
editor, press Control+J, type <a and press Control+J again, the template will be expanded to:
<a href="filename">whatever text you selected</a>
Inserting a HTML image tag [<i]
This is very similar to inserting an HTML link, as we saw above. It allows you to quickly input an <img
src="filename" alt="description" /> tag and jump between the src and alt attributes:
Trigger: <i
Template: <img src="${1:filename}" alt="${2*:description}" />$3
Insert an arbitrary HTML tag [<<]
This allows you to insert an arbitrary full HTML tag (or wrap previously selected text in the tag). To use it, simply type
<< and press Control+J. The editor will expand it to:
<|></>
Type the tag name, for example: span and press Control+J, that will result in:
<span>|</span>
You will note that the closing tag has been automatically lled with span. This is achieved with yet another feature of
placeholders, mirroring. Mirroring simply means that if you specify the sample placeholder more than once in a template,
the second and all later positions will be automatically lled in with whatever you type in the rst position, when you press
Control+J. The denition for this snippet is:
Trigger: <<
Template: <$1>${2*}</$1>$3
As you can see, the rst placeholder ($1) has been specied twice, the second time in the closing tag, which will simply
copy whatever you type in the opening tag.
108 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
Inserting an arbitrary HTML tag with a class attribute [<c]
This is very similar to the insert arbitrary tag example above, except that it assumes that you want to specify a class for
the tag:
Trigger: <c
Template: <$1 class="${2:classname}">${3*}</$1>$4
This will allow you to rst type the tag name, press Control+J, type the class name, press Control+J type the
contents of the tag and press Control+J one last time to jump out of the tag. The closing tag will be auto-lled.
Creating your own snippets
Snippets really shine because you can create your own to suit your editing style. To create your own snippets go to
Edit → Preferences → Editor settings → Manage snippets in the editor. This will pop-up an easy to use dialog to help you
create your own snippets. Simply click the Add snippet button and you will see a dialog that looks like:
First give your snippet a name, something descriptive, to help identify the snippet in the future. Then specify the trigger.
A trigger is simply the text that you have to type in the editor before pressing Control+J in order to expand the snippet.
Then specify the snippet template. You should start with one of the examples above and modify it to suit your needs.
Finally, specify which le types you want the snippet to be active for. This way you can have multiple snippets with the
same trigger text that work dierently in dierent le types.
5.8. Miscellaneous tools 109
calibre User Manual, Release 7.19.0
The next step is to test your newly created snippet. Use the Test box at the bottom. Type in the trigger text and press
Control+J to expand the snippet and jump between placeholders.
5.8.9 The Reports tool
The editor includes a nice Reports tool (via Tools → Reports) that shows summaries of the les, images, links, words,
characters and styles used in the book. Every line in the report is hot-linked. Double clicking a line jumps to the place in
the book where that item is used or dened (as appropriate). For example, in the Links view, you can double click entries
the Source column to jump to where the link is dened and entries in the Target column to jump to where the link points.
5.9 Special features in the code editor
The calibre HTML editor is very powerful. It has many features that make editing of HTML (and CSS) easier.
5.9.1 Syntax highlighting
The HTML editor has very sophisticated syntax highlighting. Features include:
The text inside bold, italic and heading tags is made bold/italic
As you move your cursor through the HTML, the matching HTML tags are highlighted, and you can jump to the
opening or closing tag with the keyboard shortcuts Ctrl+{ and Ctrl+}. Similarly, you can select the contents
of a tag with Ctrl+Alt+T or Ctrl+Shift+T.
Invalid HTML is highlighted with a red underline
Spelling errors in the text inside HTML tags and attributes such as title are highlighted. The spell checking is
language aware, based on the value of the lang attribute of the current tag and the overall book language.
CSS embedded inside <style> tags is highlighted
Special characters that can be hard to distinguish such as non-breaking spaces, dierent types of hyphens, etc. are
highlighted.
Links to other les in <a> tags, <img> and <link> tags all have the lenames highlighted. If the lename they
point to does not exist, the lename is marked with a red underline.
110 Chapter 5. Editing e-books
calibre User Manual, Release 7.19.0
5.9.2 Context sensitive help
You can right click on an HTML tag name or a CSS property name to get help for that tag or property.
You can also hold down the Ctrl key and click on any lename inside a link tag to open that le in the editor automatically.
Similarly, Ctrl clicking a class name will take you to the rst style rule that matches the tag and class.
Right clicking a class name in an HTML le will allow you to rename the class, changing all occurrences of the class
throughout the book and all its stylesheets.
5.9.3 Auto-complete
When editing an e-book, one of the most tedious tasks is creating links to other les inside the book, or to CSS stylesheets,
or images. You have to gure out the correct lename and relative path to the le. The editor has auto-complete to make
that easier.
As you type a lename, the editor automatically pops up suggestions. Simply use the Tab key to select the correct le
name. The editor even oers suggestions for links pointing to an anchor inside another HTML le. After you type the #
character, the editor will show you a list of all anchors in the target le, with a small snippet of text to help you choose
the right anchor.
Note that unlike most other completion systems, the editor’s completion system uses subsequence matching. This means
that you can type just two or three letters from anywhere in the lename to complete the lename. For example, say
you want the lename ../images/arrow1.png, you can simply type ia1 and press Tab to complete the lename.
When searching for matches, the completion system prioritizes letters that are at the start of a word, or immediately after
a path separator. Once you get used to this system, you will nd it saves you a lot of time and eort.
5.9.4 Snippets
The calibre E-book editor supports snippets. A snippet is a piece of text that is either re-used often or contains a lot of
redundant text. The editor allows you to insert a snippet with only a few key strokes. The snippets are very powerful, with
many features, such as placeholders you can jump between, automatic mirroring of repeated text and so on. For more
information, see Snippets (page 106).
5.9. Special features in the code editor 111
calibre User Manual, Release 7.19.0
112 Chapter 5. Editing e-books
CHAPTER
SIX
THE CALIBRE CONTENT SERVER
The calibre Content server allows you to access your calibre libraries and read books directly in a browser on your favorite
mobile phone or tablet device. As a result, you do not need to install any dedicated book reading/management apps on
your phone. Just use the browser. The server downloads and stores the book you are reading in an o-line cache so that
you can read it even when there is no internet connection.
Contents
Accessing the Content server from other devices (page 114)
Accessing the server from devices on your home network (page 114)
Accessing the server from anywhere on the internet (page 115)
The server interface (page 115)
The book list (page 115)
The book viewer (page 116)
Browser support (page 116)
Enabling oine support (page 116)
Managing user accounts from the command-line only (page 116)
Integrating the calibre Content server into other servers (page 117)
Using a full virtual host (page 117)
Using a URL prex (page 117)
Creating a service for the calibre server on a modern Linux system (page 119)
To start the server, click the Connect/share button and choose Start Content server. You might get a message from your
computer’s rewall or anti-virus program asking if it is OK to allow access to calibre.exe. Click the Allow or OK
button. Then open a browser (preferably Chrome or Firefox) in your computer and type in the following address:
http://127.0.0.1:8080
This will open a page in the browser showing you your calibre libraries, click on any one and browse the books in it. Click
on a book, and it will show you all the metadata about the book, along with buttons to Read and Download the book.
Click the Read button to start reading the book.
® Note
113
calibre User Manual, Release 7.19.0
The address used above http://127.0.0.1:8080 will only work on the computer that is running calibre. To
access the server from other computers/phones/tablets/etc. you will need to do a little more work, as described in the
next section.
6.1 Accessing the Content server from other devices
There are two types of remote device access that you will typically need. The rst, simpler kind is from within your home
network. If you are running calibre on a computer on your home network and you have also connected your other devices
to the same home network, then you should be easily able to access the server on those devices.
6.1.1 Accessing the server from devices on your home network
After starting the server in calibre as described above, click the Connect/share button again. Instead of the Start Content
server action, you should see a Stop Content server action instead. To the right of this action will be listed an IP address
and port number. These look like a bunch of numbers separated by periods. For example:
Stop Content server [192.168.1.5, port 8080]
These numbers tell you what address to use to connect to the server in your devices. Following the example above, the
address becomes:
http://192.168.1.5:8080
The rst part of the address is always http:// the next part is the IP address, which is the numbers before the comma
and nally we have the port number which must be added to the IP address with a colon (:). If you are lucky, that should
be all you need and you will be looking at the calibre libraries on your device. If not, read on.
Trouble-shooting the home network connection
If you are unable to access the server from your device, try the following steps:
1. Check that the server is running by opening the address http://127.0.0.1:8080 in a browser running on
the same computer as the server.
2. Check that your rewall/anti-virus is allowing connections to your computer on the port 8080 and to the calibre
program. The easiest way to eliminate the rewall/anti-virus as the source of problems is to temporarily turn them
both o and then try connecting. You should rst disconnect from the internet, before turning o the rewall, to
keep your computer safe.
3. Check that your device and computer are on the same network. This means they should both be connected to the
same wireless router. In particular neither should be using a cellular or ISP provided direct-WiFi connection.
4. If you have non-standard networking setup, it might be that the IP address shown on the Connect/share menu is
incorrect. In such a case you will have to gure out what the correct IP address to use is, yourself. Unfortunately,
given the innite diversity of network congurations possible, it is not possible to give you a roadmap for doing so.
5. If you have setup a username and password, rst try it without that to see if it is causing issues. Some e-ink devices
have browsers that do not handle authentication. You can sometimes workaround this by including the username
and password in the URL, for example: http://username:[email protected]:8080.
6. If you are stuck, you can always ask for help in the calibre user forums
43
.
43
https://www.mobileread.com/forums/forumdisplay.php?f=166
114 Chapter 6. The calibre Content server
calibre User Manual, Release 7.19.0
6.1.2 Accessing the server from anywhere on the internet
Á Warning
Before doing this you should turn on username/password protection in the server, otherwise anyone in the world will
be able to access your books. Go to Preferences → Sharing → Sharing over the net and enable the option to Require
username and password to access the content server.
While the particular details on setting up internet access vary depending on the network conguration and type of computer
you are using, the basic schema is as follows.
1. Find out the external IP address of the computer you are going to run the server on. You can do that by visiting the
site What is my IP address
44
in a browser running on the computer.
2. If the computer is behind a router, enable port forwarding on the router to forward the port 8080 (or whatever
port you choose to run the calibre Content server on) to the computer.
3. Make sure the calibre server is allowed through any rewalls/anti-virus programs on your computer.
4. Now you should be able to access the server on any internet-connected device using the IP address you found in
the rst step. For example, if the IP address you found was 123.123.123.123 and the port you are using for
the calibre server is 8080, the address to use on your device becomes: http://123.123.123.123:8080.
5. Optionally, use a service like no-ip
45
to setup an easy to remember address to use instead of the IP address you
found in the rst step.
® Note
For maximum security, you should also enable HTTPS on the Content server. You can either do so directly in the
server by providing the path to the HTTPS certicate to use in the advanced conguration options for the server, or
you can setup a reverse proxy as described below, to use an existing HTTPS setup.
6.2 The server interface
The server interface is a simplied version of the main calibre interface, optimised for use with touch screens. The home
screen shows you books you are currently reading as well as allowing to choose a calibre library you want to browse. The
server in calibre gives you access to all your libraries, not just a single one, as before.
6.2.1 The book list
The server book list is a simple grid of covers. Tap on a cover to see the detailed metadata for a book, or to read the
book. If you prefer a more detailed list, you can change the default view by clicking the three vertical dots in the top right
corner.
Sorting and searching of the book list should be familiar to calibre users. They can be accessed by clicking their icons in
the top right area. They both work exactly the same as in the main calibre program. The search page even allows you to
construct search queries by clicking on authors/tags/etc., just as you can using the Tag browser in the main program.
A much loved feature of the main program, Virtual libraries is present in the server interface as well. Click the three
vertical dots in the top right corner to choose a Virtual library.
44
https://www.whatismyip.com/
45
https://www.noip.com/free
6.2. The server interface 115
calibre User Manual, Release 7.19.0
6.2.2 The book viewer
You can read any book in your calibre library by simply tapping on it and then tapping the Read button. The book viewer
is very simple to operate. You can both tap and swipe to turn pages. Swiping up/down skips between chapters. Tapping
the top quarter of the screen gets you the detailed controls and viewer preferences.
If you leave the Content server running, you can even open the same book on multiple devices and it will remember your
last read position. If it does not you can force a sync by tapping in the top quarter and choosing Sync.
6.3 Browser support
The new calibre server makes lots of use of advanced HTML 5 and CSS 3 features. As such it requires an up-to-date
browser to use. It has been tested on Android Chrome and iOS Safari as well as Chrome and Firefox on the desktop.
The server is careful to use functionality that has either been already standardised or is on the standards track. As such if
it does not currently work with your favorite browser, it probably will once that browser has caught up.
If you are using a particularly old or limited browser or you don’t like to run JavaScript, you can use the mobile view, by
simply adding /mobile to the server address.
® Note
On iOS, Apple allows only a single browser engine, so Firefox, Chrome and Safari are all actually the same browser
under the hood. The new server interface requires iOS 10.3.2 or newer. On Android, the server has been tested with
Chrome version 58 and newer.
6.4 Enabling oine support
Browser makers have been trying to force people to use SSL by disabling advanced features in their browsers for plain
HTTP connections. One such casualty is ApplicationCache, which was what was used in calibre for oine support. As
a result now-a-days sadly, oine mode works only as long as you keep the browser tab open. In addition, in Firefox on
Android, you will need to type about:config and create a preference called browser.tabs.useCache and set
it to true.
6.5 Managing user accounts from the command-line only
The calibre program has a nice section in Preferences to allow you to manage user accounts for the server. However, if
you want to run the standalone server and cannot run the main calibre program on the same computer/user account, you
can also manage users using just the command-line.
You can manage user accounts using the --manage-users option to the standalone calibre-server program.
Suppose you want to store the user database in the folder /srv/calibre, then you create it by running:
calibre-server --userdb /srv/calibre/users.sqlite --manage-users
Just follow the prompts to create user accounts, set their permission, etc. Once you are done, you can run the server as:
calibre-server --userdb /srv/calibre/users.sqlite --enable-auth
It will use the user accounts you created in the previous step.
116 Chapter 6. The calibre Content server
calibre User Manual, Release 7.19.0
6.6 Integrating the calibre Content server into other servers
Here, we will show you how to integrate the calibre Content server into another server. The most common reason for
this is to make use of SSL or to serve the calibre library as part of a larger site. The basic technique is to run the calibre
server and setup a reverse proxy to it from the main server.
A reverse proxy is when your normal server accepts incoming requests and passes them onto the calibre server. It then
reads the response from the calibre server and forwards it to the client. This means that you can simply run the calibre
server as normal without trying to integrate it closely with your main server.
6.6.1 Using a full virtual host
The simplest conguration is to dedicate a full virtual host to the calibre server. In this case, run the calibre server as:
calibre-server
Now setup the virtual host in your main server, for example, for nginx:
http {
client_max_body_size 64M; # needed to upload large books
}
server {
listen [::]:80;
server_name myserver.example.com;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
Or, for Apache:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<VirtualHost *:80>
ServerName myserver.example.com
AllowEncodedSlashes On
ProxyPreserveHost On
ProxyPass "/" "http://localhost:8080/"
</VirtualHost>
6.6.2 Using a URL prex
If you do not want to dedicate a full virtual host to calibre, you can have it use a URL prex. Start the calibre server as:
calibre-server --url-prefix /calibre --port 8080
The key parameter here is --url-prefix /calibre. This causes the Content server to serve all URLs prexed
by /calibre. To see this in action, visit http://localhost:8080/calibre in your browser. You should see
the normal Content server website, but now it will run under /calibre.
With nginx, the required conguration is:
6.6. Integrating the calibre Content server into other servers 117
calibre User Manual, Release 7.19.0
http {
client_max_body_size 64M; # needed to upload large books
}
proxy_set_header X-Forwarded-For $remote_addr;
location /calibre/ {
proxy_buffering off;
proxy_pass http://127.0.0.1:8080$request_uri;
}
location /calibre {
# we need a trailing slash for the Application Cache to work
rewrite /calibre /calibre/ permanent;
}
For Apache, rst enable the proxy modules in Apache, by adding the following to httpd.conf:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
The exact technique for enabling the proxy modules will vary depending on your Apache installation. Once you have the
proxy modules enabled, add the following rules to httpd.conf (or if you are using virtual hosts to the conf le for the
virtual host in question):
AllowEncodedSlashes On
RewriteEngine on
RewriteRule ^/calibre/(.*) http://127.0.0.1:8080/calibre/$1 [proxy]
RedirectMatch permanent ^/calibre$ /calibre/
That’s all, you will now be able to access the calibre Content server under the /calibre URL in your main server.
The above rules pass all requests under
/calibre
to the calibre server running on port 8080 and thanks to the
--url-prefix option above, the calibre server handles them transparently.
® Note
When using a reverse proxy, you should tell the calibre Content server to only listen on localhost, by using
--listen-on 127.0.0.1. That way, the server will only listen for connections coming from the same com-
puter, i.e. from the reverse proxy.
® Note
If you have setup SSL for your main server, you should tell the calibre server to use basic authentication instead of
digest authentication, as it is faster. To do so, pass the --auth-mode=basic option to calibre-server.
118 Chapter 6. The calibre Content server
calibre User Manual, Release 7.19.0
6.7 Creating a service for the calibre server on a modern Linux sys-
tem
You can easily create a service to run calibre at boot on a modern (systemd
46
) based Linux system. Just create the le
/etc/systemd/system/calibre-server.service with the contents shown below:
[Unit]
Description=calibre Content server
After=network.target
[Service]
Type=simple
User=mylinuxuser
Group=mylinuxgroup
ExecStart=/opt/calibre/calibre-server "/path/to/calibre library folder"
[Install]
WantedBy=multi-user.target
Change mylinuxuser and mylinuxgroup to whatever user and group you want the server to run as. This should
be the same user and group that own the les in the calibre library folder. Note that it is generally not a good idea to run
the server as root. Also change the path to the calibre library folder to suit your system. You can add multiple libraries if
needed. See the help for the calibre-server command.
Now run:
sudo systemctl start calibre-server
to start the server. Check its status with:
sudo systemctl status calibre-server
To make it start at boot, run:
sudo systemctl enable calibre-server
® Note
The calibre server does not need a running X server, but it does need the X libraries installed as some components it
uses link against them.
® Note
The calibre server also supports systemd socket activation, so you can use that, if needed, as well.
46
https://www.freedesktop.org/wiki/Software/systemd/
6.7. Creating a service for the calibre server on a modern Linux system 119
calibre User Manual, Release 7.19.0
120 Chapter 6. The calibre Content server
CHAPTER
SEVEN
COMPARING E-BOOKS
calibre includes an integrated e-book comparison tool that can be used to see what has changed inside an e-book after
editing or converting it. It can compare books in the EPUB and AZW3 formats.
To use it, either open the e-book in the tool for Editing e-books (page 79) and then click File → Compare to other book or
use the Book details (page 20) panel. If you do a conversion from EPUB to EPUB, the original EPUB le will be saved as
ORIGINAL_EPUB. Simply right click on the ORIGINAL_EPUB entry in the Book details panel and choose Compare
to EPUB format.
The comparison tool that opens will look like the screenshot below. It shows you the dierences in text, styles and images
in the chosen books.
121
calibre User Manual, Release 7.19.0
7.1 Understanding the comparison view
As can be seen in the screenshot above, the comparison view shows the dierences between the two books side by side.
Only the dierences, with a few lines of context around them are shown. This makes it easy to see at a glance only what
was changed inside a large document like a book.
Added text is shown with a green background, removed text with a red background and changed text with a blue back-
ground.
The line numbers of all changed text are show at the sides, making it easy to go to a particular change in the editor. When
you open the comparison tool from within the editor, you can also double click on a line in the right panel to go to that
line in the editor automatically.
One useful technique when comparing books is to tell the comparison tool to beautify the text and style les before
calculating dierences. This can often result in cleaner and easier to follow dierences. To do this, click the Options
122 Chapter 7. Comparing e-books
calibre User Manual, Release 7.19.0
button in the bottom right and choose Beautify les before comparing. Note that beautifying can sometimes have undesired
eects, as it can cause invalid markup to be altered to make it valid. You can also change the number of lines of context
shown around dierences via the Options button.
You can search for any text in the dierences via the Search bar at the bottom. You will need to specify which panel to
search, the Left or the Right.
7.2 Launching the comparison tool
The comparison tool is most useful when you have two versions of the same book and you want to see what is dierent
between them. To that end, there are several ways to launch the tool.
7.2.1 Comparing two e-book les
Open the rst le in the Editing e-books (page 79) tool. Now click File → Compare to another book and choose the second
le (it must be in the same format as the rst). The comparison view will open with the le being edited on the right and
the second le on the left.
7.2.2 Comparing the ORIGINAL_FMT to FMT
When you do a conversion in calibre from a FMT to itself, the original le is saved as ORIGINAL_FMT. You can see
what was changed by the conversion, by right clicking on the ORIGINAL_FMT entry in the Book details (page 20) panel
in the main calibre window and selecting Compare to FMT. The comparison view will open with ORIGINAL_FMT on
the left and FMT on the right.
7.2.3 Comparing a checkpoint to the current state of the book while editing
The Editing e-books (page 79) tool has a very useful feature, called Checkpoints (page 91). This allows you to save the
current state of the book as a named checkpoint, to which you can revert if you do not like the changes you have made
since creating the checkpoint. Checkpoints are also created automatically when you perform various automated actions
in the editor. You can see the list of checkpoints by going to View → Checkpoints and then use the Compare button to
compare the book at the selected checkpoint with the current state. The comparison tool will show the checkpoint on the
left and the current state on the right.
7.2. Launching the comparison tool 123
calibre User Manual, Release 7.19.0
124 Chapter 7. Comparing e-books
CHAPTER
EIGHT
EDITING E-BOOK METADATA
Contents
Editing the metadata of one book at a time (page 125)
Downloading metadata (page 126)
Managing book formats (page 126)
All about covers (page 126)
Editing the metadata of many books at a time (page 126)
Search and replace (page 126)
Bulk downloading of metadata (page 128)
Adding extra data les to a book (page 128)
E-books come in all shapes and sizes and more often than not, their metadata (things like title/author/series/publisher) is
incomplete or incorrect. The simplest way to change metadata in calibre is to simply double click on an entry and type in
the correct replacement. For more sophisticated, “power editing” use the edit metadata tools discussed below.
8.1 Editing the metadata of one book at a time
Click the book you want to edit and then click the Edit metadata button or press the E key. A dialog opens that allows
you to edit all aspects of the metadata. It has various features to make editing faster and more ecient. A list of the
commonly used tips:
You can click the button in between title and authors to swap them automatically.
You can click the button next to author sort to have calibre automatically ll it in using the sort values stored with
each author. Use the Manage authors dialog to see and change the authors’ sort values. This dialog can be opened
by clicking and holding the button next to author sort.
You can click the button next to tags to use the Tag editor to manage the tags associated with the book.
The “Ids” box can be used to enter an ISBN (and many other types of id), it will have a red background if you enter
an invalid ISBN. It will be green for valid ISBNs.
The author sort box will be red if the author sort value diers from what calibre thinks it should be.
125
calibre User Manual, Release 7.19.0
8.1.1 Downloading metadata
The nicest feature of the edit metadata dialog is its ability to automatically ll in many metadata elds by getting metadata
from various websites. Currently, calibre uses Google Books and Amazon. The metadata download can ll in Title,
author, series, tags, rating, description and ISBN for you.
To use the download, ll in the title and author elds and click the Fetch metadata button. calibre will present you with a
list of books that most closely match the title and author. If you ll in the ISBN eld rst, it will be used in preference
to the title and author. If no matches are found, try making your search a little less specic by including only some key
words in the title and only the author last name.
8.1.2 Managing book formats
In calibre, a single book entry can have many dierent formats associated with it. For example you may have obtained
the Complete Works of Shakespeare in EPUB format and later converted it to MOBI to read on your Kindle. calibre
automatically manages multiple formats for you. In the Available formats section of the Edit metadata dialog, you can
manage these formats. You can add a new format, delete an existing format and also ask calibre to set the metadata and
cover for the book entry from the metadata in one of the formats.
8.1.3 All about covers
You can ask calibre to download book covers for you, provided the book has a known ISBN. Alternatively you can specify
a le on your computer to use as the cover. calibre can even generate a default cover with basic metadata on it for you.
You can drag and drop images onto the cover to change it and also right click to copy/paste cover images.
In addition, there is a button to automatically trim borders from the cover, in case your cover image has an ugly border.
8.2 Editing the metadata of many books at a time
First select the books you want to edit by holding Ctrl or Shift and clicking on them. If you select more than one
book, clicking the Edit metadata button will cause the Bulk metadata edit dialog to open. Using this dialog, you can
quickly set the author/publisher/rating/tags/series etc of a bunch of books to the same value. This is particularly useful
if you have just imported a number of books that have some metadata in common. This dialog is very powerful, for
example, it has a Search and replace tab that you can use to perform bulk operations on metadata and even copy metadata
from one column to another.
The normal edit metadata dialog also has Next and Previous buttons that you can use to edit the metadata of several books
one after the other.
8.2.1 Search and replace
The Edit metadata for many books dialog allows you to perform arbitrarily powerful search and replace operations on the
selected books. By default it uses a simple text search and replace, but it also support regular expressions. For more on
regular expressions, see All about using regular expressions in calibre (page 215).
As noted above, there are two search and replace modes: character match and regular expression. Character match will
look in the Search eld you choose for the characters you type in the search for box and replace those characters with
what you type in the replace with box. Each occurrence of the search characters in the eld will be replaced. For example,
assume the eld being searched contains a bad cat. If you search for a to be replaced with HELLO, then the result will
be HELLO bHELLOd cHELLOt.
126 Chapter 8. Editing e-book metadata
calibre User Manual, Release 7.19.0
If the eld you are searching on is a multiple eld like tags, then each tag is treated separately. For example, if your tags
contain Horror, Scary, the search expression r, will not match anything because the expression will rst be applied to
Horror and then to Scary.
If you want the search to ignore upper/lowercase dierences, uncheck the Case sensitive box.
You can have calibre change the case of the result (information after the replace has happened) by choosing one of the
functions from the Apply function after replace box. The operations available are:
Lower case change all the characters in the eld to lower case
Upper case change all the characters in the eld to upper case
Title case capitalize each word in the result.
The Your test box is provided for you to enter text to check that search/replace is doing what you want. In the majority
of cases the book test boxes will be sucient, but it is possible that there is a case you want to check that isn’t shown in
these boxes. Enter that case into Your test.
Regular expression mode has some dierences from character mode, beyond (of course) using regular expressions. The
rst is that functions are applied to the parts of the string matched by the search string, not the entire eld. The second is
that functions apply to the replacement string, not to the entire eld.
The third and most important is that the replace string can make reference to parts of the search string by using backref-
erences. A backreference is \\n where n is an integer that refers to the n’th parenthesized group in the search expression.
For example, given the same example as above, a bad cat, a search expression a (…) (…), and a replace expression a
\2 \1, the result will be a cat bad. Please see the All about using regular expressions in calibre (page 215) for more
information on backreferences.
One useful pattern: assume you want to change the case of an entire eld. The easiest way to do this is to use character
mode, but lets further assume you want to use regular expression mode. The search expression should be (^.*$), the
replace expression should be \1, and the desired case change function should be selected.
Finally, in regular expression mode you can copy values from one eld to another. Simply make the source and destination
eld dierent. The copy can replace the destination eld, prepend to the eld (add to the front), or append to the eld
(add at the end). The ‘use comma’ checkbox tells calibre to (or not to) add a comma between the text and the destination
eld in prepend and append modes. If the destination is multiple (e.g., tags), then you cannot uncheck this box.
Search and replace is done after all the other metadata changes in the other tabs are applied. This can lead to some
confusion, because the test boxes will show the information before the other changes, but the operation will be applied
after the other changes. If you have any doubts about what is going to happen, do not mix search/replace with other
changes.
8.2. Editing the metadata of many books at a time 127
calibre User Manual, Release 7.19.0
8.2.2 Bulk downloading of metadata
If you want to download the metadata for multiple books at once, right-click the Edit metadata button and select Download
metadata. You can choose to download only metadata, only covers, or both.
8.3 Adding extra data les to a book
calibre can store any number of extra data les associated to a book. These can be alternate covers, supplementary
material, etc. They cannot be viewed directly or used as conversion sources. Nor are they indexed by the Full text search
engine in calibre. To view/add/delete them select the book and right click the Edit metadata button and choose Manage
data les. This will pop-up a window where you can perform operations on these les. Alternately, you can right click
the Add books button and choose Add data les to selected book records to more quickly add data les.
128 Chapter 8. Editing e-book metadata
CHAPTER
NINE
FREQUENTLY ASKED QUESTIONS
Contents
E-book format conversion (page 129)
Device integration (page 132)
Library management (page 139)
Miscellaneous (page 144)
9.1 E-book format conversion
Contents
What formats does calibre support conversion to/from? (page 130)
What are the best source formats to convert? (page 130)
I converted a PDF le, but the result has various problems? (page 130)
How do I convert my le containing non-English characters, or smart quotes? (page 130)
What’s the deal with Table of Contents in MOBI les? (page 131)
How do I convert a collection of HTML les in a specic order? (page 131)
The EPUB I produced with calibre is not valid? (page 132)
How do I use some of the advanced features of the conversion tools? (page 132)
129
calibre User Manual, Release 7.19.0
9.1.1 What formats does calibre support conversion to/from?
calibre supports the conversion of many input formats to many output formats. It can convert every input format in the
following list, to every output format.
Input Formats: AZW, AZW3, AZW4, CBZ, CBR, CB7, CBC, CHM, DJVU, DOCX, EPUB, FB2, FBZ, HTML,
HTMLZ, LIT, LRF, MOBI, ODT, PDF, PRC, PDB, PML, RB, RTF, SNB, TCR, TXT, TXTZ
Output Formats: AZW3, EPUB, DOCX, FB2, HTMLZ, OEB, LIT, LRF, MOBI, PDB, PMLZ, RB, PDF, RTF, SNB,
TCR, TXT, TXTZ, ZIP
® Note
PRC is a generic format, calibre supports PRC les with TextRead and MOBIBook headers. PDB is also a generic
format. calibre supports eReader, Plucker (input only), PML and zTxt PDB les. DJVU support is only for converting
DJVU les that contain embedded text. These are typically generated by OCR software. MOBI books can be of two
types Mobi6 and KF8. calibre fully supports both. MOBI les often have .azw or .azw3 le extensions. DOCX les
from Microsoft Word 2007 and newer are supported.
9.1.2 What are the best source formats to convert?
In order of decreasing preference: LIT, MOBI, AZW, EPUB, AZW3, FB2, FBZ, DOCX, HTML, PRC, ODT, RTF,
PDB, TXT, PDF
9.1.3 I converted a PDF le, but the result has various problems?
PDF is a terrible format to convert from. For a list of the various issues you will encounter when converting PDF, see:
Convert PDF documents (page 73).
9.1.4 How do I convert my le containing non-English characters, or smart quotes?
There are two aspects to this problem:
1. Knowing the encoding of the source le: calibre tries to guess what character encoding your source les use,
but often, this is impossible, so you need to tell it what encoding to use. This can be done in the GUI via the
Input character encoding eld in the Look & feel → Text section of the conversion dialog. The command-line
tools have an ebook-convert-txt-input --input-encoding (page 340) option.
2. When adding HTML les to calibre, you may need to tell calibre what encoding the les are in. To do this
go to Preferences → Advanced → Plugins → File type and customize the HTML to ZIP plugin, telling it what
encoding your HTML les are in. Now when you add HTML les to calibre they will be correctly processed.
HTML les from dierent sources often have dierent encodings, so you may have to change this setting
repeatedly. A common encoding for many les from the web is cp1252 and I would suggest you try that
rst. Note that when converting HTML les, leave the input encoding setting mentioned above blank. This
is because the HTML to ZIP plugin automatically converts the HTML les to a standard encoding (UTF-8).
130 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
9.1.5 What’s the deal with Table of Contents in MOBI les?
The rst thing to realize is that most e-books have two tables of contents. One is the traditional Table of Contents, like
the ToC you nd in paper books. This Table of Contents is part of the main document ow and can be styled however
you like. This ToC is called the
content ToC
.
Then there is the metadata ToC. A metadata ToC is a ToC that is not part of the book text and is typically accessed by
some special button on a reader. For example, in the calibre E-book viewer, you use the Show Table of Contents button
to see this ToC. This ToC cannot be styled by the book creator. How it is represented is up to the viewer program.
In the MOBI format, the situation is a little confused. This is because the MOBI format, alone amongst mainstream
e-book formats, does not have decent support for a metadata ToC. A MOBI book simulates the presence of a metadata
ToC by putting an extra content ToC at the end of the book. When you click Go to Table of Contents on your Kindle, it
is to this extra content ToC that the Kindle takes you.
Now it might well seem to you that the MOBI book has two identical ToCs. Remember that one is semantically a content
ToC and the other is a metadata ToC, even though both might have exactly the same entries and look the same. One can
be accessed directly from the Kindle’s menus, the other cannot.
When converting to MOBI, calibre detects the metadata ToC in the input document and generates an end-of-le ToC in
the output MOBI le. You can turn this o by an option in the MOBI Output settings. You can also tell calibre whether
to put it at the start or the end of the book via an option in the MOBI Output settings. Remember this ToC is semantically
a metadata ToC, in any format other than MOBI it cannot not be part of the text. The fact that it is part of the text in
MOBI is an accident caused by the limitations of MOBI. If you want a ToC at a particular location in your document text,
create one by hand. So we strongly recommend that you leave the default as it is, i.e. with the metadata ToC at the end
of the book. Also note that if you disable the generation of the end-of-le ToC the resulting MOBI le may not function
correctly on a Kindle, since the Kindle’s use the metadata ToC for many things, including the Page Flip feature.
If you have a hand edited ToC in the input document, you can use the ToC detection options in calibre to automatically
generate the metadata ToC from it. See the conversion section of the User Manual for more details on how to use these
options.
Finally, I encourage you to ditch the content ToC and only have a metadata ToC in your e-books. Metadata ToCs will give
the people reading your e-books a much superior navigation experience (except on the Kindle, where they are essentially
the same as a content ToC).
® Note
The newer AZW3 format has proper support for a metadata ToC. However, the Kindle rmware tends to malfunction
if you disable the generation of the end-of-le inline ToC. So it is recommended that you leave the generated ToC
alone. If you create an AZW3 le with a metadata ToC and no end-of-le generated ToC, some features on the Kindle
will not work, such as the Page Flip feature.
9.1.6 How do I convert a collection of HTML les in a specic order?
In order to convert a collection of HTML les in a specic order, you have to create a table of contents le. That is,
another HTML le that contains links to all the other les in the desired order. Such a le looks like:
<html>
<body>
<h1>Table of Contents</h1>
<p style="text-indent:0pt">
<a href="file1.html">First File</a><br/>
<a href="file2.html">Second File</a><br/>
.
(continues on next page)
9.1. E-book format conversion 131
calibre User Manual, Release 7.19.0
(continued from previous page)
.
.
</p>
</body>
</html>
Then, just add this HTML le to the GUI and use the Convert button to create your e-book. You can use the option in
the Table of Contents section in the conversion dialog to control how the Table of Contents is generated.
® Note
By default, when adding HTML les, calibre follows links in the les in depth rst order. This means that if le
A.html links to B.html and C.html and D.html, but B.html also links to D.html, then the les will be in the order
A.html, B.html, D.html, C.html. If instead you want the order to be A.html, B.html, C.html, D.html then you must
tell calibre to add your les in breadth rst order. Do this by going to Preferences → Advanced → Plugins → File type
and customizing the HTML to ZIP plugin.
9.1.7 The EPUB I produced with calibre is not valid?
calibre does not guarantee that an EPUB produced by it is valid. The only guarantee it makes is that if you feed it valid
XHTML 1.1 + CSS 2.1 it will output a valid EPUB. calibre tries hard to ensure that EPUBs it produces actually work as
intended on a wide variety of devices, a goal that is incompatible with producing valid EPUBs, and one that is far more
important to the vast majority of its users. If you need a tool that always produces valid EPUBs, calibre is not for you.
This means, that if you want to send a calibre produced EPUB to an online store that uses an EPUB validity checker, you
have to make sure that the EPUB is valid yourself, calibre will not do it for you in other words you must feed calibre
valid XHTML + CSS as the input documents.
9.1.8 How do I use some of the advanced features of the conversion tools?
You can get help on any individual feature of the converters by mousing over it in the GUI or running ebook-convert
dummy.html .epub -h at a terminal. A good place to start is to look at the following demo le that demonstrates
some of the advanced features html-demo.zip
47
.
9.2 Device integration
Contents
What devices does calibre support? (page 133)
How can I help get my device supported in calibre? (page 133)
My device is not being detected by calibre? (page 134)
My device is non-standard or unusual. What can I do to connect to it? (page 134)
How do I use calibre with my iPad/iPhone/iPod touch? (page 134)
47
https://calibre-ebook.com/downloads/html-demo.zip
132 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
How do I use calibre with my Android phone/tablet or Kindle Fire? (page 135)
Can I access my calibre books using the web browser in my Kindle or other reading device? (page 136)
I cannot send emails using calibre? (page 136)
My device is getting mounted read-only in Linux, so calibre cannot connect to it? (page 137)
Why does calibre not support collections on the Kindle or shelves on the Nook? (page 138)
I am getting an error when I try to use calibre with my Kobo Touch/Glo/etc.? (page 138)
Covers for books I send to my e-ink Kindle show up momentarily and then are replaced by a generic cover?
(page 138)
The covers for my MOBI les have stopped showing up in Kindle for PC/Kindle for Android/iPad etc. (page 139)
I transferred some books to my Kindle using calibre and they did not show up? (page 139)
9.2.1 What devices does calibre support?
calibre can directly connect to all the major (and most of the minor) e-book reading devices, smartphones, tablets, etc.
In addition, using the Connect to folder function you can use it with any e-book reader that exports itself as a USB disk.
Finally, you can connect wirelessly to any device that has a web browser using the calibre Content server.
9.2.2 How can I help get my device supported in calibre?
If your device appears as a USB disk to the operating system, adding support for it to calibre is very easy. We just need
some information from you:
Complete list of e-book formats that your device supports.
Is there a special folder on the device in which all e-book les should be placed? Also does the device detect les
placed in sub-folders?
We also need information about your device that calibre will collect automatically. First, if your device supports
SD cards, insert them. Then connect your device to the computer. In calibre go to Preferences → Miscellaneous
and click the “Debug device detection” button. This will create some debug output. Copy it to a le and repeat the
process, this time with your device disconnected from your computer.
Send both the above outputs to us with the other information and we will write a device driver for your device.
Once you send us the output for a particular operating system, support for the device in that operating system will appear
in the next release of calibre. To send us the output, open a bug report and attach the output to it. See how to report
bugs
48
.
48
https://calibre-ebook.com/bugs
9.2. Device integration 133
calibre User Manual, Release 7.19.0
9.2.3 My device is not being detected by calibre?
Follow these steps to nd the problem:
Make sure that you are connecting only a single device to your computer at a time. Do not have another calibre
supported device like an iPhone/iPad etc. at the same time.
If you are connecting an Apple iDevice (iPad, iPod Touch, iPhone), Apple no longer allows third party software
to connect to their devices using a USB cable. Instead use a wireless connection, via the calibre Content server.
If you are connecting a Kindle Fire or other Android device, read the note under Using a USB cable (page 135).
On macOS if you get permission errors when connecting a device to calibre, you can x that by looking under
System Preferences > Security and Privacy > Privacy > Files and Folders.
Make sure you are running the latest version of calibre (currently 7.19.0). The latest version can always be down-
loaded from the calibre website
49
. You can tell what version of calibre you are currently running by looking at the
bottom line of the main calibre window.
Ensure your operating system is seeing the device. That is, the device should show up in Windows Explorer (in
Windows) or Finder (in macOS).
In calibre, go to Preferences → Ignored Devices and check that your device is not being ignored
If all the above steps fail, go to Preferences → Miscellaneous and click Debug device detection with your device
attached and post the output as a ticket on the calibre bug tracker
50
.
9.2.4 My device is non-standard or unusual. What can I do to connect to it?
In addition to the Connect to folder function found under the Connect/share button, calibre provides a User defined
device plugin that can be used to connect to any USB device that shows up as a disk drive in your operating system.
Note: on Windows, the device must have a drive letter for calibre to use it. See the device plugin Preferences ->
Plugins -> Device plugins -> User defined and Preferences -> Miscellaneous -> Get
information to setup the user defined device for more information. Note that if you are using the
user dened plugin for a device normally detected by a builtin calibre plugin, you must disable the builtin plugin rst, so
that your user dened plugin is used instead.
9.2.5 How do I use calibre with my iPad/iPhone/iPod touch?
An easy way to browse your calibre collection from your Apple device is by using The calibre Content server (page 113),
which makes your collection available over the net. First perform the following steps in calibre
Set the Preferred Output Format in calibre to EPUB (The output format can be set under Prefer-
ences → Interface → Behavior)
Set the output prole to iPad (this will work for iPhone/iPods as well), under Preferences → Conversion → Common
options → Page setup
Convert the books you want to read on your iDevice to EPUB format by selecting them and clicking the Convert
button.
Turn on the Content server by clicking the Connect/share button and leave calibre running. You can also tell calibre
to automatically start the Content server via Preferences → Sharing → Sharing over the net.
The Content server allows you to read books directly in Safari itself. In addition, there are many apps for your iDevice
that can connect to the calibre Content server. Examples include: Marvin, Mapleread and iBooks itself.
49
https://calibre-ebook.com/download
50
https://bugs.launchpad.net/calibre
134 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
Using the Content server
Start the Safari browser and type in the IP address and port of the computer running the calibre server, like this:
http://192.168.1.2:8080/
Replace 192.168.1.2 with the local IP address of the computer running calibre. See The calibre Content server
(page 113) for details on running the server and nding out the right IP address to use.
You will see a list of books in Safari, tap on any book and you will be given the option to either download it, or read it in
the browser itself. If you choose to download it, Safari will ask you if you want to open it with iBooks.
Many reading apps support browsing the calibre library directly via its OPDS support. In such apps you can go to the
online catalog screen and add the IP address of the calibre server to browse and download books from your calibre library
within the app.
9.2.6 How do I use calibre with my Android phone/tablet or Kindle Fire?
There are two ways that you can connect your Android device to calibre. Using a USB cable or wirelessly, over the air.
The rst step to using an Android device is installing an e-book reading application on it. There are many free and paid
e-book reading applications for Android: Some examples (in no particular order): FBReader
51
, Moon+
52
, Mantano
53
,
Aldiko
54
, Kindle
55
.
Using a USB cable
Simply plug your device into the computer with a USB cable. calibre should automatically detect the device and then you
can transfer books to it by clicking the Send to device button. Note that on macOS and Linux only a single program can
connect to an Android device at a time, so make sure the device is not opened in the OS File manager, or the Android
File Transfer utility, etc.
® Note
With newer Android devices, you might have to jump through a few hoops to get the connection working, as Google
really does not want you to be independent of its cloud. First, unlock the screen before plugging in the USB cable.
When you plugin in the USB cable you will get a popup notication. Make sure it says some thing like “Transferring
Media les” or “MTP (Media Transfer mode)”. If it does not, tap the notication, and change the mode to Media
Transfer (MTP). You may need to restart calibre at this point in order for your device to be recognized. Finally, you
might get a popup on the device every time calibre or the operating system actually tries to connect to it, asking for
permission, tap OK.
® Note
With the Kindle Fire 8 or newer there is an icon that shows up when the USB cable is plugged in, showing that the
device is charging. Tap that and switch the device to data transfer mode, and then start calibre, it should then be
detected.
51
https://play.google.com/store/apps/details?id=org.geometerplus.zlibrary.ui.android&hl=en
52
https://play.google.com/store/apps/details?id=com.flyersoft.moonreader&hl=en
53
https://play.google.com/store/apps/details?id=com.mantano.reader.android.lite&hl=en
54
https://play.google.com/store/apps/details?id=com.aldiko.android&hl=en
55
https://play.google.com/store/apps/details?id=com.amazon.kindle&feature=related_apps
9.2. Device integration 135
calibre User Manual, Release 7.19.0
Over the air
calibre has a builtin web server, the calibre Content server (page 113). It makes your calibre collection available over the
net. You can browse it on your device using a simple browser or a dedicated application. First perform the following
steps in calibre:
Set the Preferred Output Format in calibre to EPUB for normal Android devices or MOBI for Kindles (The output
format can be set under Preferences → Interface → Behavior)
Convert the books you want to read on your device to EPUB/MOBI format by selecting them and clicking the
Convert button.
Turn on the Content server in calibre’s preferences and leave calibre running.
Now on your Android device, open the browser and browse to
http://192.168.1.2:8080/
Replace 192.168.1.2 with the local IP address of the computer running calibre. See The calibre Content server
(page 113) for details on running the server and nding out the right IP address to use.
You can now browse your book collection and download books from calibre to your device to open with whatever e-book
reading software you have on your Android device.
Many reading apps support browsing the calibre library directly via its OPDS support. In such apps you can go to the
online catalog screen and add the IP address of the calibre server to browse and download books from your calibre library
within the app.
9.2.7 Can I access my calibre books using the web browser in my Kindle or other
reading device?
calibre has a Content server that exports the books in calibre as a web page. See The calibre Content server (page 113) for
details.
Some devices, like the Kindle (1/2/DX), do not allow you to access port 8080 (the default port on which the content server
runs). In that case, change the port in the calibre Preferences to 80. (On some operating systems, you may not be able to
run the server on a port number less than 1024 because of security settings. In this case the simplest solution is to adjust
your router to forward requests on port 80 to port 8080).
Also some devices do not have browsers advanced enough to run the app-like interface used by the Content server. For
such devices, you can simply add /mobile to the server URL to get a simplied, non-JavaScript interface.
9.2.8 I cannot send emails using calibre?
Because of the large amount of spam in email, sending email can be tricky, as dierent mail servers use dierent strategies
to block email. The most common problem is if you are sending email directly (without a mail relay) in calibre. Many
servers (for example, Amazon) block email that does not come from a well known relay. The most robust way to setup
email sending in calibre is to do the following:
Create a free GMX account at GMX
56
.
Go to Preferences → Sharing → Sharing books by email in calibre and click the Use GMX button and ll in the
information asked for.
Log into your GMX account on the website and enable SMTP sending (Settings->POP3 & IMAP->Send and receive
emails via external program)
56
https://www.gmx.com
136 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
calibre will then be able to use GMX to send the mail.
If you are sending to your Kindle, remember to update the email preferences on your Amazon Kindle page to allow
email sent from your GMX email address. Also note that Amazon does not allow email delivery of AZW3 and
new style (KF8) MOBI les. Finally, Amazon recently started sending conrmation emails that you have to click
on back to your GMX account before the book is actually delivered.
Even after doing this, you may have problems. One common source of problems is that some poorly designed antivirus
programs block calibre from opening a connection to send email. Try adding an exclusion for calibre in your antivirus
program.
® Note
Microsoft/GMX can disable your account if you use it to send large amounts of email. So, when using these services
to send mail calibre automatically restricts itself to sending one book every ve minutes. If you don’t mind risking your
account being blocked you can reduce this wait interval by going to Preferences → Advanced → Tweaks in calibre.
® Note
Google recently deliberately broke their email sending protocol (SMTP) support in an attempt to force everyone to use
their web interface so they can show you more ads. They are trying to claim that SMTP is insecure, that is incorrect
and simply an excuse. Use some other email provider instead.
® Note
If you are concerned about giving calibre access to your email account, simply create a new free email account with
GMX or Outlook and use it only for calibre.
9.2.9 My device is getting mounted read-only in Linux, so calibre cannot connect
to it?
Linux kernels mount devices read-only when their lesystems have errors. You can repair the lesystem with:
sudo fsck.vfat -y /dev/sdc
Replace /dev/sdc with the path to the device node of your device. You can nd the device node of your device, which
will always be under /dev by examining the output of:
mount
9.2. Device integration 137
calibre User Manual, Release 7.19.0
9.2.10 Why does calibre not support collections on the Kindle or shelves on the
Nook?
Neither the Kindle nor the Nook provide any way to manipulate collections over a USB connection. If you really care
about using collections, I would urge you to sell your Kindle/Nook and get a Kobo. Only Kobo seems to understand that
life is too short to be entering collections one by one on an e-ink screen
Note that in the case of the Kindle, there is a way to manipulate collections via USB, but it requires that the Kindle be
rebooted every time it is disconnected from the computer, for the changes to the collections to be recognized. As such,
it is unlikely that any calibre developers will ever feel motivated enough to support it. There is however, a calibre plugin
that allows you to create collections on your Kindle from the calibre metadata. It is available from here
57
.
® Note
Amazon have removed the ability to manipulate collections completely in their newer models, like the Kindle Touch
and Kindle Fire, making even the above plugin useless, unless you root your Kindle and install custom rmware.
9.2.11 I am getting an error when I try to use calibre with my Kobo Touch/Glo/etc.?
The Kobo has very buggy rmware. Connecting to it has been known to fail at random. Certain combinations of moth-
erboard, USB ports/cables/hubs can exacerbate this tendency to fail. If you are getting an error when connecting to your
touch with calibre try the following, each of which has solved the problem for some calibre users.
Connect the Kobo directly to your computer, not via USB Hub
Try a dierent USB cable and a dierent USB port on your computer
Log out of the Kobo and log in again, this causes it to rebuild the database, xing corrupted database errors.
Try upgrading the rmware on your Kobo Touch to the latest
Try resetting the Kobo (sometimes this cures the problem for a little while, but then it re-appears, in which case
you have to reset again and again)
Try only putting one or two books onto the Kobo at a time and do not keep large collections on the Kobo
9.2.12 Covers for books I send to my e-ink Kindle show up momentarily and then
are replaced by a generic cover?
This happens because of an Amazon bug. They try to download a cover for the book from their servers and when that
fails, they replace the existing cover that calibre created with a generic cover. For details see this forum thread
58
. As of
version 4.17, calibre has a workaround, where if you connect the Kindle to calibre after the covers have been destroyed
by Amazon, calibre will restore them automatically. So in order to see the covers on your Kindle, you have to:
1) Send the book to the Kindle with calibre
2) Disconnect the Kindle and wait for Amazon to destroy the cover
3) Reconnect the Kindle to calibre
Note that this workaround only works for books sent with calibre 4.17 or later. Alternately, simply keep your Kindle in
airplane mode, you don’t really want Amazon knowing every book you read anyway. I encourage you to contact Amazon
customer support and complain loudly about this bug. Maybe Amazon will listen.
57
https://www.mobileread.com/forums/showthread.php?t=244202
58
https://www.mobileread.com/forums/showthread.php?t=329945
138 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
® Note
If the workaround is not working for you make sure you Kindle rmware is at least version 5.12.5, released in April
2020.
9.2.13 The covers for my MOBI les have stopped showing up in Kindle for
PC/Kindle for Android/iPad etc.
This is caused by a bug in the Amazon software. You can work around it by going to Preferences → Conversion → Output
Options → MOBI output and setting the Enable sharing of book content option. If you are reconverting a previously
converted book, you will also have to enable the option in the conversion dialog for that individual book (as per book
conversion settings are saved and take precedence).
Note that doing this will mean that the generated MOBI will show up under personal documents instead of Books on
the Kindle Fire and Amazon whispersync will not work, but the covers will. It’s your choice which functionality is more
important to you. I encourage you to contact Amazon and ask them to x this bug.
The bug in Amazon’s software is that when you put a MOBI le on a Kindle, unless the le is marked as a Personal
document, Amazon assumes you bought the book from it and tries to download the cover thumbnail for it from its servers.
When the download fails, it refuses to fallback to the cover dened in the MOBI le. This is likely deliberate on Amazon’s
part to try to force authors to sell only through them. In other words, the Kindle only displays covers for books marked
as Personal Documents or books bought directly from Amazon.
If you send a MOBI le to an e-ink Kindle with calibre using a USB connection, calibre works around this Amazon bug by
uploading a cover thumbnail itself. However, that workaround is only possible when using a USB connection and sending
with calibre. Note that if you send using email, Amazon will automatically mark the MOBI le as a Personal Document
and the cover will work, but the book will show up in Personal Documents.
9.2.14 I transferred some books to my Kindle using calibre and they did not show
up?
Books sent to the Kindle only show up on the Kindle after they have been indexed by the Kindle. This can take some
time. If the book still does not show up after some time, then it is likely that the Kindle indexer crashed. Sometimes a
particular book can cause the indexer to crash. Unfortunately, Amazon has not provided any way to deduce which book
is causing a crash on the Kindle. Your only recourse is to either reset the Kindle, or delete all les from its memory using
Windows Explorer (or whatever le manager you use) and then send the books to it again, one by one, until you discover
the problem book. Once you have found the problem book, delete it o the Kindle and do a MOBI to MOBI or MOBI
to AZW3 conversion in calibre and then send it back. This will most likely take care of the problem.
9.3 Library management
Contents
Where are the book les stored? (page 140)
How does calibre manage author names and sorting? (page 140)
Why doesn’t calibre let me store books in my own folder structure? (page 141)
9.3. Library management 139
calibre User Manual, Release 7.19.0
Why doesn’t calibre have a column for foo? (page 142)
Can I have a column showing the formats or the ISBN? (page 142)
How do I move my calibre data from one computer to another? (page 142)
The list of books in calibre is blank! (page 143)
I am getting errors with my calibre library on a networked drive/NAS? (page 144)
9.3.1 Where are the book les stored?
When you rst run calibre, it will ask you for a folder in which to store your books. Whenever you add a book to calibre,
it will copy the book into that folder. Books in the folder are nicely arranged into sub-folders by Author and Title. Note
that the contents of this folder are automatically managed by calibre, do not add any les/folders manually to this folder,
as they may be automatically deleted. If you want to add a le associated to a particular book, use the top right area of
Edit metadata dialog to do so. Then, calibre will automatically put that le into the correct folder and move it around
when the title/author changes.
Metadata about the books is stored in the le metadata.db at the top level of the library folder. This le is a sqlite
database. When backing up your library make sure you copy the entire folder and all its sub-folders.
The library folder and all its contents make up what is called a calibre library. You can have multiple such libraries. To
manage the libraries, click the calibre icon on the toolbar. You can create new libraries, remove/rename existing ones and
switch between libraries easily.
You can copy or move books between dierent libraries (once you have more than one library setup) by right clicking on
a book and selecting the Copy to library action.
9.3.2 How does calibre manage author names and sorting?
Author names are complex, especially across cultures, see this note
59
for some of the complexities. calibre has a very
exible strategy for managing author names. The rst thing to understand is that books and authors are separate entities
in calibre. A book can have more than one author, and an author can have more than one book. You can manage the
authors of a book by the edit metadata dialog. You can manage individual authors by right clicking on the author in the
Tag browser on the left of the main calibre window and selecting Manage authors. Using this dialog you can change the
name of an author and also how that name is sorted. This will automatically change the name of the author in all the
books of that author. When a book has multiple authors, separate their names using the & character.
Now coming to author name sorting:
When a new author is added to calibre (this happens whenever a book by a new author is added), calibre automat-
ically computes a sort string for both the book and the author.
Authors in the Tag browser are sorted by the sort value for the authors. Remember that this is dierent from the
Author sort eld for a book.
By default, this sort algorithm assumes that the author name is in First name Last name format and generates
a Last name, First name sort value.
You can change this algorithm by going to Preferences → Advanced → Tweaks and setting the au-
thor_sort_copy_method tweak.
59
https://www.w3.org/International/questions/qa-personal-names.en.php?changelang=en
140 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
You can force calibre to recalculate the author sort values for every author by right clicking on any author and
selecting Manage authors, then pushing the Recalculate all author sort values button. Do this after you have set the
author_sort_copy_method tweak to what you want.
You can force calibre to recalculate the author sort values for all books by using the bulk metadata edit dialog (select
all books and click edit metadata, check the Automatically set author sort checkbox, then press OK).
When recalculating the author sort values for books, calibre uses the author sort values for each individual author.
Therefore, ensure that the individual author sort values are correct before recalculating the books’ author sort values.
You can control whether the Tag browser display authors using their names or their sort values by setting the
categories_use_eld_for_author_name tweak in Preferences → Advanced → Tweaks
Note that you can set an individual author’s sort value to whatever you want using Manage authors. This is useful when
dealing with names that calibre will not get right, such as complex multi-part names like Miguel de Cervantes Saavedra
or when dealing with Asian names like Sun Tzu.
With all this exibility, it is possible to have calibre manage your author names however you like. For example, one
common request is to have calibre display author names LN, FN. To do this, and if the note below does not apply to you,
then:
Set the author_sort_copy_method tweak to copy as described above.
Restart calibre. Do not change any book metadata before doing the remaining steps.
Change all author names to LN, FN using the Manage authors dialog.
After you have changed all the authors, press the Recalculate all author sort values button.
Press OK, at which point calibre will change the authors in all your books. This can take a while.
® Note
When changing from FN LN to LN, FN, it is often the case that the values in author_sort are already in LN,
FN format. If this is your case, then do the following:
Set the author_sort_copy_method tweak to copy as described above.
Restart calibre. Do not change any book metadata before doing the remaining steps.
Open the Manage authors dialog. Press the copy all author sort values to author
button.
Check through the authors to be sure you are happy. You can still press Cancel to abandon the changes.
Once you press OK, there is no undo.
Press OK, at which point calibre will change the authors in all your books. This can take a while.
9.3.3 Why doesn’t calibre let me store books in my own folder structure?
The whole point of calibre’s library management features is that they provide a search and sort based interface for locating
books that is much more ecient than any possible folder scheme you could come up with for your collection. Indeed, once
you become comfortable using calibre’s interface to nd, sort and browse your collection, you won’t ever feel the need to
hunt through the les on your disk to nd a book again. By managing books in its own folder structure of Author -> Title
-> Book les, calibre is able to achieve a high level of reliability and standardization. To illustrate why a search/tagging
based interface is superior to folders, consider the following. Suppose your book collection is nicely sorted into folders
with the following scheme:
Genre -> Author -> Series -> ReadStatus
9.3. Library management 141
calibre User Manual, Release 7.19.0
Now this makes it very easy to nd for example all science ction books by Isaac Asimov in the Foundation series. But
suppose you want to nd all unread science ction books. There’s no easy way to do this with this folder scheme, you
would instead need a folder scheme that looks like:
ReadStatus -> Genre -> Author -> Series
In calibre, you would instead use tags to mark genre and read status and then just use a simple search query like
tag:scifi and not tag:read. calibre even has a nice graphical interface, so you don’t need to learn its
search language instead you can just click on tags to include or exclude them from the search.
To those of you that claim that you need access to the lesystem, so that you can have access to your books over the
network, calibre has an excellent Content server that gives you access to your calibre library over the net.
If you are worried that someday calibre will cease to be developed, leaving all your books marooned in its folder structure,
explore the powerful Save to disk feature in calibre that lets you export all your les into a folder structure of arbitrary
complexity based on their metadata.
Finally, the reason there are numbers at the end of every title folder, is for robustness. That number is the id number of
the book record in the calibre database. The presence of the number allows you to have multiple records with the same
title and author names. It is also part of what allows calibre to magically regenerate the database with all metadata if the
database le gets corrupted. Given that calibre’s mission is to get you to stop storing metadata in lenames and stop using
the lesystem to nd things, the increased robustness aorded by the id numbers is well worth the uglier folder names.
If you are still not convinced, then I’m afraid calibre is not for you. Look elsewhere for your book cataloguing needs. Just
so we’re clear, this is not going to change. Kindly do not contact us in an attempt to get us to change this.
9.3.4 Why doesn’t calibre have a column for foo?
calibre is designed to have columns for the most frequently and widely used elds. In addition, you can add any columns
you like. Columns can be added via Preferences → Interface → Add your own columns. Watch the tutorial UI Power tips
60
to learn how to create your own columns, or read this blog post
61
.
You can also create “virtual columns” that contain combinations of the metadata from other columns. In the add column
dialog use the Quick create links to easily create columns to show the book ISBN or formats. You can use the powerful
calibre template language to do much more with columns. For more details, see The calibre template language (page 161).
9.3.5 Can I have a column showing the formats or the ISBN?
Yes, you can. Follow the instructions in the answer above for adding custom columns.
9.3.6 How do I move my calibre data from one computer to another?
You can export all calibre data (books, settings and plugins) and then import it on another computer. First let’s see how
to export the data:
Right click the calibre icon in the main calibre toolbar and select Export/import all calibre data. Note that if there is
currently a device connected, this menu option will not be available so, disconnect any connected devices. Then
click the button labelled Export all your calibre data. You will see a list of all your calibre libraries. Click OK and
choose an empty folder somewhere on your computer. The exported data will be saved in this folder. Simply copy
this folder to your new computer and follow the instructions below to import the data.
60
https://calibre-ebook.com/demo#tutorials
61
https://blog.calibre-ebook.com/calibre-custom-columns/
142 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
Install calibre on your new computer and run through the Welcome wizard, it does not matter what you do there, as
you will be importing your old settings in the next step. You will now have an empty calibre, with just the Getting
Started guide in your library. Once again, right click the calibre button and choose Export/import all calibre data.
Then click the button labelled Import previously exported data. Select the folder with the exported data that you
copied over earlier. You will now have a list of libraries you can import. Go through the list one by one, and select
the new location for each library (a location is just an empty folder somewhere on your computer). Click OK. After
the import completes, calibre will restart, with all your old libraries, settings and calibre plugins.
® Note
This import/export functionality is only available from calibre version 2.47 onwards. If you have an older version
of calibre, or if you encounter problems with the import/export, you can just copy over your calibre library folder
manually, as described in the next paragraph.
Simply copy the calibre library folder from the old to the new computer. You can nd out what the library folder is
by clicking the calibre icon in the toolbar. Choose the Switch/create calibre library action and you will see the path to
the current calibre library.
Now on the new computer, start calibre for the rst time. It will run the Welcome wizard asking you for the location
of the calibre library. Point it to the previously copied folder. If the computer you are transferring to already has a
calibre installation, then the Welcome wizard won’t run. In that case, right-click the calibre icon in the toolbar and
point it to the newly copied folder. You will now have two calibre libraries on your computer and you can switch
between them by clicking the calibre icon on the toolbar. Transferring your library in this manner preserves all your
metadata, tags, custom columns, etc.
9.3.7 The list of books in calibre is blank!
In order to understand why that happened, you have to understand what a calibre library is. At the most basic level, a
calibre library is just a folder. Whenever you add a book to calibre, that book’s les are copied into this folder (arranged
into sub folders by author and title). Inside the calibre library folder, at the top level, you will see a le called metadata.db.
This le is where calibre stores the metadata like title/author/rating/tags etc. for every book in your calibre library. The
list of books that calibre displays is created by reading the contents of this metadata.db le.
There can be two reasons why calibre is showing a empty list of books:
Your calibre library folder changed its location. This can happen if it was on an external disk and the drive letter
for that disk changed. Or if you accidentally moved the folder. In this case, calibre cannot nd its library and so
starts up with an empty library instead. To remedy this, do a right-click on the calibre icon in the calibre toolbar
and select Switch/create library. Click the little blue icon to select the new location of your calibre library and click
OK. If you don’t know the new location search your computer for the le metadata.db.
Your metadata.db le was deleted/corrupted. In this case, you can ask calibre to rebuild the metadata.db from
its backups. Right click the calibre icon in the calibre toolbar and select Library maintenance->Restore database.
calibre will automatically rebuild metadata.db.
9.3. Library management 143
calibre User Manual, Release 7.19.0
9.3.8 I am getting errors with my calibre library on a networked drive/NAS?
Do not put your calibre library on a networked drive.
A lesystem is a complex beast. Most network lesystems lack various lesystem features that calibre uses. Some don’t
support le locking, some don’t support hardlinking, some are just aky. Additionally, calibre is a single user application,
if you accidentally run two copies of calibre on the same networked library, bad things will happen. Finally, dierent
OSes impose dierent limitations on lesystems, so if you share your networked drive across OSes, once again, bad things
will happen.
Consider using the calibre Content server to make your books available on other computers. Run calibre on a single
computer and access it via the Content server or a Remote Desktop solution.
If you must share the actual library, use a le syncing tool like DropBox or rsync instead of a networked drive. If you are
using a le-syncing tool it is essential that you make sure that both calibre and the le syncing tool do not try to access
the calibre library at the same time. In other words, do not run the le syncing tool and calibre at the same time.
Even with these tools there is danger of data corruption/loss, so only do this if you are willing to live with that risk. In
particular, be aware that Google Drive is incompatible with calibre, if you put your calibre library in Google Drive, you
will suer data loss. See this thread
62
for details.
9.4 Miscellaneous
Contents
Amazon is stopping email delivery of MOBI les? (page 145)
I want calibre to download news from my favorite news website. (page 145)
Why the name calibre? (page 146)
Why does calibre show only some of my fonts on macOS? (page 146)
calibre is not starting on Windows? (page 146)
calibre freezes/crashes occasionally? (page 147)
The calibre E-book viewer and Edit book tools do not work on Windows? (page 147)
Using the viewer or doing any conversions results in a permission denied error on Windows (page 148)
calibre is not starting/crashing on macOS? (page 148)
I get only a black or white screen when running the calibre E-book viewer? (page 148)
I downloaded the installer, but it is not working? (page 149)
My antivirus program claims calibre is a virus/trojan? (page 149)
How do I backup calibre? (page 149)
How do I use purchased EPUB books with calibre (or what do I do with .acsm les)? (page 150)
I am getting a “Permission Denied” error? (page 150)
Can I have the comment metadata show up on my reader? (page 150)
How do I get calibre to use my HTTP proxy? (page 151)
62
https://www.mobileread.com/forums/showthread.php?t=205581
144 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
I want some feature added to calibre. What can I do? (page 151)
Why doesn’t calibre have an automatic update? (page 151)
How is calibre licensed? (page 152)
How do I run calibre from my USB stick? (page 152)
How do I run parts of calibre like news download and the Content server on my own Linux server? (page 152)
9.4.1 Amazon is stopping email delivery of MOBI les?
Amazon have announced
63
that they will stop accepting MOBI les emailed to @kindle.com email addresses. You
can instruct calibre to send EPUB instead of MOBI by going to Preferences → Sharing books by email and then removing
MOBI from the list of formats to send to your @kindle.com email address and adding EPUB instead.
Note however, that Amazon’s EPUB intake is very awed, they will reject a number of EPUB les that work everywhere
else. In such cases you can try the following trick:
1. Convert the EPUB le to MOBI
2. Then convert the MOBI le back to EPUB and send the resulting EPUB le
This will remove all advanced formatting, embedded fonts, etc., but greatly increase the chances of Amazon accepting
the EPUB.
® Note
If you were previously using email delivery of periodicals downloaded by calibre, you will be better o sending those
by USB cable or downloading them from the calibre Content server via the Kindle’s built-in browser. However, if
you want to continue using email delivery you can try changing the output format in Preferences->Behavior to EPUB,
then calibre will download the news in EPUB format. Whether Amazon will accept the EPUB or not is a whole other
question.
9.4.2 I want calibre to download news from my favorite news website.
If you are reasonably procient with computers, you can teach calibre to download news from any website of your choos-
ing. To learn how to do this see Adding your favorite news website (page 31).
Otherwise, you can request a particular news site by posting in the calibre Recipes forum
64
.
63
https://blog.the-ebook-reader.com/2022/05/03/amazon-dropping-mobi-support-on-send-to-kindle-apps/
64
https://www.mobileread.com/forums/forumdisplay.php?f=228
9.4. Miscellaneous 145
calibre User Manual, Release 7.19.0
9.4.3 Why the name calibre?
Take your pick:
Converter And LIBRary for E-books
A high calibre product
A tribute to the SONY Librie which was the rst e-ink based e-book reader
My wife chose it ;-)
calibre is pronounced as cal-i-ber not ca-li-bre. If you’re wondering, calibre is the British/commonwealth spelling for
caliber. Being Indian, that’s the natural spelling for me.
9.4.4 Why does calibre show only some of my fonts on macOS?
calibre embeds fonts in e-book les it creates. E-book les support embedding only TrueType and OpenType (.ttf and .otf)
fonts. Most fonts on macOS systems are in .dfont format, thus they cannot be embedded. calibre shows only TrueType
and OpenType fonts found on your system. You can obtain many such fonts on the web. Simply download the .ttf/.otf
les and add them to the Library/Fonts folder in your home folder.
9.4.5 calibre is not starting on Windows?
There can be several causes for this:
If you get no errors but the calibre window does not appear, it has probably just appeared o screen. You can
gather all windows onto the current screen using one of the techniques described here
65
.
If you get an error about calibre not being able to open a le because it is in use by another program, do the
following:
Uninstall calibre
Reboot your computer
Re-install calibre. But do not start calibre from the installation wizard.
Temporarily disable your antivirus program (disconnect from the Internet before doing so, to be safe)
Look inside the folder you chose for your calibre library. If you see a le named metadata.db, delete it.
Start calibre
From now on you should be able to start calibre normally.
If you get an error about a Python function terminating unexpectedly after upgrading calibre, rst uninstall cal-
ibre, then delete the folders (if they exists) C:\Program Files\Calibre and C:\Program Files\
Calibre2. Now re-install and you should be ne.
If you get an error in the Welcome wizard on an initial run of calibre, try choosing a folder like C:\library as
the calibre library (calibre sometimes has trouble with library locations if the path contains non-English characters,
or only numbers, etc.)
Try running it as administrator (Right click on the icon and select Run as administrator)
If it still won’t launch, start a command prompt (press the Windows key and R; then type cmd.exe in the Run dialog
that appears). At the command prompt type the following command and press Enter:
65
https://www.wikihow.com/Bring-an-Off-Screen-Window-Back-on-Windows
146 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
calibre-debug -g
Post any output you see in a help message on the Forum
66
.
9.4.6 calibre freezes/crashes occasionally?
There are several possible things I know of, that can cause this:
You recently connected an external monitor or TV to your computer. In this case, whenever calibre opens a new
window like the edit metadata window or the conversion dialog, it appears on the second monitor where you don’t
notice it and so you think calibre has frozen. Disconnect your second monitor and restart calibre.
The following programs have been reported to cause crashes in calibre: If you are running any of these, close
them before starting calibre, or uninstall them: RoboForm, Logitech SetPoint Settings, Constant Guard Protection by
Xnity, Spybot, Killer Network Manager, Nahimic UI Interface, Acronis True Image.
You are using a Wacom branded USB mouse/tablet. There is an incompatibility between Wacom drivers and the
graphics toolkit calibre uses. Try using a non-Wacom mouse.
On some 64 bit versions of Windows there are security software/settings that prevent 64-bit calibre from working
properly. If you are using the 64-bit version of calibre try switching to the 32-bit version.
If the crash happens when you are trying to copy text from the calibre E-book viewer, it is most likely caused by
some clipboard monitoring/managing application you have running. Turn it o and you should be ne.
If the crashes happen specically when you are using a le dialog, like clicking on the Add books button or the
Save to Disk button, then you have some software that has installed broken Shell extensions on your computer.
Known culprits include:
SpiderOak
,
odrive sync
and
Dell Backup and Recovery
and
NetDrive
. If you have one of
these, uninstall them and you will be ne. You can also use the NirSoft Shell Extension Viewer
67
to see what shell
extensions are installed on your system and disable them individually, if you don’t want to uninstall the full program.
Remember to use “Restart Explorer” or reboot your computer after disabling the shell extensions.
If none of the above apply to you, then there is some other program on your computer that is interfering with calibre.
First reboot your computer in safe mode, to have as few running programs as possible, and see if the crashes still happen.
If they do not, then you know it is some program causing the problem. The most likely such culprit is a program that
modies other programs’ behavior, such as an antivirus, a device driver, something like RoboForm (an automatic form
lling app) or an assistive technology like Voice Control or a Screen Reader.
The only way to nd the culprit is to eliminate the programs one by one and see which one is causing the issue. Basically,
stop a program, run calibre, check for crashes. If they still happen, stop another program and repeat.
9.4.7 The calibre E-book viewer and Edit book tools do not work on Windows?
These two programs use hardware acceleration as they embed a version of the Chrome browser to render HTML. If they
do not work it will be because of incompatibility with your system’s GPU (graphics) drivers. Try updating these rst, and
reboot. If that does not x it, you can set the QTWEBENGINE_CHROMIUM_FLAGS environment variable to the value
--disable-gpu to turn o hardware acceleration. See this page
68
for details.
66
https://www.mobileread.com/forums/forumdisplay.php?f=166
67
https://www.nirsoft.net/utils/shexview.html
68
https://doc.qt.io/qt-6/qtwebengine-debugging.html
9.4. Miscellaneous 147
calibre User Manual, Release 7.19.0
9.4.8 Using the viewer or doing any conversions results in a permission denied
error on Windows
Something on your computer is preventing calibre from accessing its own temporary les. Most likely the permissions on
your Temp folder are incorrect. Go to the folder le:C:\Users\USERNAME\AppData\Local in Windows Explorer and
then right click on the le:Temp folder, select Properties and go to the Security tab. Make sure that your user account has
full control for this folder.
Some users have reported that running the following command in an Administrator Command Prompt xed their permis-
sions. To get an Administrator Command Prompt search for cmd.exe in the start menu, then right click on the command
prompt entry and select Run as administrator. At the command prompt type the following command and press Enter:
icacls "%appdata%\..\Local\Temp" /reset /T
Alternately, you can run calibre as Administrator, but doing so will cause some functionality, such as drag and drop to
not work.
Finally, some users have reported that disabling UAC xes the problem.
9.4.9 calibre is not starting/crashing on macOS?
One common cause of failures on macOS is the use of accessibility technologies that are incompatible with the graphics
toolkit calibre uses. Try turning o VoiceOver if you have it on. Also go to System Preferences->System->Universal
Access and turn o the setting for enabling access for assistive devices in all the tabs. Another cause can be some third
party apps that modify system behavior, such as Smart Scroll.
You can obtain debug output about why calibre is not starting by running Console.app. Debug output will be printed to
it. If the debug output contains a line that looks like:
Qt: internal: -108: Error ATSUMeasureTextImage text/qfontengine_mac.mm
then the problem is probably a corrupted font cache. You can clear the cache by following these instructions
69
. If that
doesn’t solve it, look for a corrupted font le on your system, in ~/Library/Fonts or the like. An easy way to check
for corrupted fonts in macOS is to start the “Font Book” application, select all fonts and then in the File menu, choose
“Validate fonts”.
9.4.10 I get only a black or white screen when running the calibre E-book viewer?
This will be because of an incompatibility between Qt WebEngine, which the viewer uses to render and the GPU drivers on
your system. First try upgrading the GPU drivers. If that does not help, you can try turning o hardware acceleration in Qt
WebEngine by setting the environment variable QTWEBENGINE_CHROMIUM_FLAGS to the value --disable-gpu.
See Environment variables (page 290) for how to change environment variables.
69
https://www.macworld.com/article/1139383/fontcacheclear.html
148 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
9.4.11 I downloaded the installer, but it is not working?
Downloading from the Internet can sometimes result in a corrupted download. If the calibre installer you downloaded is
not opening, try downloading it again. If re-downloading it does not work, download it from an alternate location
70
. If
the installer still doesn’t work, then something on your computer is preventing it from running.
Try temporarily disabling your antivirus program (Microsoft Security Essentials, or Kaspersky or Norton or
McAfee or whatever). This is most likely the culprit if the upgrade process is hanging in the middle.
Similarly, if the installer is failing/rolling back and you have Microsoft PowerToys running, quit it.
If you have installed to a non-standard location, try running the installer as Administrator
Try rebooting your computer and running a registry cleaner like Wise registry cleaner
71
.
Try a clean install. That is, uninstall calibre, delete C:\Program Files\Calibre2 (or wherever you previ-
ously chose to install calibre). Then re-install calibre. Note that uninstalling does not touch your books or settings.
Try downloading the installer with an alternate browser. For example if you are using Microsoft Edge, try using
Firefox or Chrome instead.
If you get an error about a missing DLL on Windows, then most likely, the permissions on your temporary folder
are incorrect. Go to the folder C:\Users\USERNAME\AppData\Local in Windows Explorer and then right
click on the Temp folder and select Properties and go to the Security tab. Make sure that your user account has full
control for this folder.
If you still cannot get the installer to work and you are on Windows, you can use the calibre portable install
72
, which does
not need an installer (it is just a ZIP le).
9.4.12 My antivirus program claims calibre is a virus/trojan?
The rst thing to check is that you are downloading calibre from the ocial website
73
. Make sure you are clicking the
download links on the left, not the advertisements on the right. calibre is a very popular program and unscrupulous people
try to setup websites oering it for download to fool the unwary.
If you have the ocial download and your antivirus program is still claiming calibre is a virus, then, your antivirus
program is wrong. Antivirus programs use heuristics, patterns of code that “look suspicious” to detect viruses. It’s rather
like racial proling. calibre is a completely open source product. You can actually browse the source code yourself (or
hire someone to do it for you) to verify that it is not a virus. Please report the false identication to whatever company you
buy your antivirus software from. If the antivirus program is preventing you from downloading/installing calibre, disable
it temporarily, install calibre and then re-enable it.
9.4.13 How do I backup calibre?
The most important thing to backup is the calibre library folder, that contains all your books and metadata. This is the
folder you chose for your calibre library when you ran calibre for the rst time. You can get the path to the library folder
by clicking the calibre icon on the main toolbar. You must backup this complete folder with all its les and sub-folders.
You can switch calibre to using a backed up library folder by simply clicking the calibre icon on the toolbar and choosing
your backup library folder. A backed up library folder backs up your custom columns and saved searches as well as all
your books and metadata.
70
https://github.com/kovidgoyal/calibre/releases/latest
71
https://www.wisecleaner.com
72
https://calibre-ebook.com/download_portable
73
https://calibre-ebook.com/download
9.4. Miscellaneous 149
calibre User Manual, Release 7.19.0
If you want to backup the calibre conguration/plugins, you have to backup the cong folder. You can nd this cong
folder via Preferences → Miscellaneous. Note that restoring conguration folders is not ocially supported, but should
work in most cases. Just copy the contents of the backup folder into the current conguration folder to restore.
9.4.14 How do I use purchased EPUB books with calibre (or what do I do with .acsm
les)?
Most purchased EPUB books have DRM (page 391). This prevents calibre from opening them. You can still use calibre
to store and transfer them to your e-book reader. First, you must authorize your reader on a Windows machine with
Adobe Digital Editions. Once this is done, EPUB books transferred with calibre will work ne on your reader. When
you purchase an epub book from a website, you will get an “.acsm” le. This le should be opened with Adobe Digital
Editions, which will then download the actual “.epub” e-book. The e-book le will be stored in the folder “My Digital
Editions”, from where you can add it to calibre.
9.4.15 I am getting a “Permission Denied” error?
A permission denied error can occur because of many possible reasons, none of them having anything to do with calibre.
You can get permission denied errors if you are using an SD card with write protect enabled.
On macOS if you get permission errors when connecting a device to calibre, you can x that by looking under
System Preferences > Security and Privacy > Privacy > Files and Folders.
If you, or some program you used changed the le permissions of the les in question to read only.
If there is a lesystem error on the device which caused your operating system to mount the lesystem in read only
mode or mark a particular le as read only pending recovery.
If the les have their owner set to a user other than you.
If your le is open in another program.
If the le resides on a device, you may have reached the limit of a maximum of 256 les in the root of the device.
In this case you need to reformat the device/sd card referred to in the error message with a FAT32 lesystem, or
delete some les from the SD card/device memory.
You will need to x the underlying cause of the permissions error before resuming to use calibre. Read the error message
carefully, see what le it points to and x the permissions on that le or its containing folders.
9.4.16 Can I have the comment metadata show up on my reader?
Most readers do not support this. You should complain to the manufacturer about it and hopefully if enough people
complain, things will change. In the meantime, you can insert the metadata, including comments into a “Jacket page” at
the start of the e-book, by using the option to “Insert metadata as page at start of book” during conversion. The option is
found in the Structure detection section of the conversion settings. Note that for this to have eect you have to convert the
book. If your book is already in a format that does not need conversion, you can convert from that format to the same
format.
Another alternative is to create a catalog in e-book form containing a listing of all the books in your calibre library, with
their metadata. Click-and-hold the Convert button to access the catalog creation tool. And before you ask, no you cannot
have the catalog “link directly to” books on your reader.
150 Chapter 9. Frequently Asked Questions
calibre User Manual, Release 7.19.0
9.4.17 How do I get calibre to use my HTTP proxy?
By default, calibre uses whatever proxy settings are set in your OS. Sometimes these are incorrect, for example, on
Windows if you don’t use Microsoft Edge then the proxy settings may not be up to date. You can tell calibre to use
a particular proxy server by setting the
http_proxy
and
https_proxy
environment variables. The format of the
variable is: http://username:password@servername you should ask your network administrator to give you
the correct value for this variable. Note that calibre only supports HTTP proxies not SOCKS proxies. You can see the
current proxies used by calibre in Preferences->Miscellaneous.
9.4.18 I want some feature added to calibre. What can I do?
You have two choices:
1. Create a patch by hacking on calibre and send it to me for review and inclusion. See Development
74
.
2. Open a bug requesting the feature
75
. Remember that while you may think your feature request is extremely
important/essential, calibre developers might not agree. Fortunately, calibre is open source, which means you
always have the option of implementing your feature yourself, or hiring someone to do it for you. Furthermore,
calibre has a comprehensive plugin architecture, so you might be able to develop your feature as a plugin, see
Writing your own plugins to extend calibre’s functionality (page 226).
9.4.19 Why doesn’t calibre have an automatic update?
For many reasons:
There is no need to update every week. If you are happy with how calibre works turn o the update notication and
be on your merry way. Check back to see if you want to update once a year or so. There is a check box to turn o
the update notication, on the update notication itself.
calibre downloads currently use about 150TB of bandwidth a month
76
. Implementing automatic updates would
greatly increase that and end up costing thousands of dollars a month, which someone has to pay.
If I implement a dialog that downloads the update and launches it, instead of going to the website as it does now,
that would save the most ardent calibre updater,
at most ve clicks a week
. There are far higher priority things to
do in calibre development.
If you really, really hate downloading calibre every week but still want to be up to the latest, I encourage you to run
from source, which makes updating trivial. Instructions are available here (page 361).
There are third party automatic updaters for calibre made by calibre users in the calibre forum
77
.
74
https://calibre-ebook.com/get-involved
75
https://calibre-ebook.com/bugs
76
https://calibre-ebook.com/dynamic/downloads
77
https://www.mobileread.com/forums/forumdisplay.php?f=238
9.4. Miscellaneous 151
calibre User Manual, Release 7.19.0
9.4.20 How is calibre licensed?
calibre is licensed under the GNU General Public License v3 (an open source license). This means that you are free
to redistribute calibre as long as you make the source code available. So if you want to put calibre on a CD with your
product, you must also put the calibre source code on the CD. The source code is available for download
78
. You are free
to use the results of conversions from calibre however you want. You cannot use either code or libraries from calibre in
your software without making your software open source. For details, see The GNU GPL v3
79
.
9.4.21 How do I run calibre from my USB stick?
A portable version of calibre is available here
80
.
9.4.22 How do I run parts of calibre like news download and the Content server on
my own Linux server?
First, you must install calibre onto your Linux server. If your server is using a modern Linux distribution, you should
have no problems installing calibre onto it.
® Note
calibre needs GLIBC >= 2.31 and libstdc++ >= 6.0.28. If you have an older server, you will either need to compile
these from source, or use calibre 3.48 which requires GLIBC >= 2.17 or 2.85.1 which requires GLIBC >= 2.13 or
calibre 1.48 which requires only GLIBC >= 2.10. In addition, although the calibre command line utilities do not need
a running X server, some of them do require the X server libraries to be installed on your system. This is because
of Qt, which is used for various image processing tasks, and links against these libraries. If you get an ImportError
about some Qt modules, you are likely missing some X libraries. Typical candidates are: libxcb-cursor0,
libxcb-xinerama0, libegl1, libopengl0.
You can run the calibre server via the command:
/opt/calibre/calibre-server /path/to/the/library/you/want/to/share
You can download news and convert it into an e-book with the command:
/opt/calibre/ebook-convert "Title of news source.recipe" outputfile.epub
If you want to generate MOBI, use outputfile.mobi instead and use --output-profile kindle.
You can email downloaded news with the command:
/opt/calibre/calibre-smtp
I leave guring out the exact command line as an exercise for the reader.
Finally, you can add downloaded news to the calibre library with:
/opt/calibre/calibredb add --with-library /path/to/library outfile.epub
Remember to read the Command Line Interface (page 303) section of the calibre User Manual to learn more about these,
and other commands.
78
https://download.calibre-ebook.com
79
https://www.gnu.org/licenses/gpl.html
80
https://calibre-ebook.com/download_portable
152 Chapter 9. Frequently Asked Questions
CHAPTER
TEN
TUTORIALS
Here you will nd tutorials to get you started using calibre’s more advanced features, such as XPath and templates.
10.1 Managing subgroups of books, for example “genre”
Some people wish to organize the books in their library into subgroups, similar to subfolders. The most commonly
provided reason is to create genre hierarchies, but there are many others. One user asked for a way to organize textbooks
by subject and course number. Another wanted to keep track of gifts by subject and recipient. This tutorial will use the
genre example for the rest of this post.
Before going on, please note that we are not talking about folders on the hard disk. Subgroups are not le folders. Books
will not be copied anywhere. calibre’s library le structure is not aected. Instead, we are presenting a way to organize
and display subgroups of books within a calibre library.
Setup (page 155)
Searching (page 157)
Restrictions (page 157)
Useful template functions (page 158)
The commonly-provided requirements for subgroups such as genres are:
A subgroup (e.g., a genre) must contain (point to) books, not categories of books. This is what distinguishes
subgroups from calibre user categories.
A book can be in multiple subgroups (genres). This distinguishes subgroups from physical le folders.
Subgroups (genres) must form a hierarchy; subgroups can contain subgroups.
Tags give you the rst two. If you tag a book with the genre then you can use the Tag browser (or search) to nd the
books with that genre, giving you the rst. Many books can have the same tag(s), giving you the second. The problem is
that tags don’t satisfy the third requirement. They don’t provide a hierarchy.
153
calibre User Manual, Release 7.19.0
The calibre hierarchy feature gives you the third the abil-
ity to see the genres in a ‘tree’ and the ability to easily search for books in genre or sub-genre. For example, assume that
your genre structure is similar to the following:
Genre
. History
.. Japanese
.. Military
.. Roman
. Mysteries
.. English
.. Vampire
. Science Fiction
.. Alternate History
.. Military
.. Space Opera
. Thrillers
.. Crime
.. Horror
etc.
By using the hierarchy feature, you can see these genres in the Tag browser in tree form, as shown in the screen image.
In this example the outermost level (Genre) is a custom column that contains the genres. Genres containing sub-genres
appear with a small triangle next to them. Clicking on that triangle will open the item and show the sub-genres, as you
can see with History and Science Fiction.
Clicking on a genre can search for all books with that genre or children of that genre. For example, clicking on Science
Fiction can give all three of the child genres, Alternate History, Military, and Space Opera. Clicking on Alternate History
will give books in that genre, ignoring those in Military and Space Opera. Of course, a book can have multiple genres. If
a book has both Space Opera and Military genres, then you will see that book if you click on either genre. Searching is
discussed in more detail below.
Another thing you can see from the image is that the genre Military appears twice, once under History and once under
Science Fiction. Because the genres are in a hierarchy, these are two separate genres. A book can be in one, the other,
or (doubtfully in this case) both. For example, the books in Winston Churchill’s “The Second World War” could be in
154 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
“History.Military”. David Weber’s Honor Harrington books could be in “Science Fiction.Military”, and for that matter
also in “Science Fiction.Space Opera.”
Once a genre exists, that is at least one book has that genre, you can easily apply it to other books by dragging the books
from the library view onto the genre you want the books to have. You can also apply genres in the metadata editors; more
on this below.
10.1.1 Setup
By now, your question might be “How was all of this setup?” There are three steps: 1) create the custom column, 2) tell
calibre that the new column is to be treated as a hierarchy, and 3) add genres.
You create the custom column in the usual way, using Preferences -> Add your own columns. This example uses “#genre”
as the lookup name and “Genre” as the column heading. It is important that the column type is set to Comma-separated
text, like tags, shown in the Tag browser.
Then after restarting calibre, you must tell calibre that the column is to be treated as a hierarchy. Go to Preferences  → 
Look & feel  →  Tag browser  →  Hierarchy and searching and choose the new Genre column as having hierarchical items.
At the point there are no genres in the column. We are left with the last step: how to apply a genre to a book. A genre
does not exist in calibre until it appears on at least one book. To learn how to apply a genre for the rst time, we must go
into some detail about what a genre looks like in the metadata for a book.
A hierarchy of ‘things’ is built by creating an item consisting of phrases separated by periods. Continuing the genre
example, these items would “History.Military”, “Mysteries.Vampire”, “Science Fiction.Space Opera”, etc. Thus to create
a new genre, you pick a book that should have that genre, edit its metadata, and enter the new genre into the column you
created. Continuing our example, if you want to assign a new genre “Comics” with a sub-genre “Superheroes” to a book,
you would ‘edit metadata’ for that (comic) book, choose the Custom metadata tab, and then enter “Comics.Superheroes”
as shown in the following (ignore the other custom columns):
10.1. Managing subgroups of books, for example “genre” 155
calibre User Manual, Release 7.19.0
After doing the above, you see in the Tag browser:
From here on, to apply this new genre to a book (a comic book, presumably), you can either drag the book onto the genre,
or add it to the book using edit metadata in exactly the same way as done above.
® Note
Hierarchical display only works if the Tag browser is set to sort items by name. This is the default and can be checked
by clicking the Congure button at the bottom of the Tag browser.
156 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.1.2 Searching
The easiest way to search for genres is using the Tag browser, clicking on the genre you wish to see. Clicking on a genre
with children will show you books with that genre and all child genres. However, this might bring up a question. Just
because a genre has children doesn’t mean that it isn’t a genre in its own right. For example, a book can have the genre
“History” but not “History.Military”. How do you search for books with only “History”?
The Tag browser search mechanism knows if an item has children. If it does, clicking on the item cycles through 5
searches instead of the normal three. The rst is the normal green plus, which shows you books with that genre only (e.g.,
History). The second is a doubled plus (shown above), which shows you books with that genre and all sub-genres (e.g.,
History and History.Military). The third is the normal red minus, which shows you books without that exact genre. The
fourth is a doubled minus, which shows you books without that genre or sub-genres. The fth is back to the beginning,
no mark, meaning no search.
10.1.3 Restrictions
If you search for a genre then create a saved search for it, you can use the ‘restrict to’ box to create a Virtual library of
books with that genre. This is useful if you want to do other searches within the genre or to manage/update metadata for
books in the genre. Continuing our example, you can create a Saved search named ‘History.Japanese’ by rst clicking on
the genre Japanese in the Tag browser to get a search into the search eld, entering History.Japanese into the saved search
eld, then pushing the “Save search” button (the green box with the white plus, on the right-hand side).
After creating the saved search, you can use it as a restriction.
10.1. Managing subgroups of books, for example “genre” 157
calibre User Manual, Release 7.19.0
10.1.4 Useful template functions
You might want to use the genre information in a template, such as with save to disk or send to device. The
question might then be “How do I get the outermost genre name or names?” A calibre template function,
subitems, is provided to make doing this easier.
For example, assume you want to add the outermost genre level to the save-to-disk template to make genre
folders, as in “History/The Gathering Storm - Churchill, Winston”. To do this, you must extract the rst
level of the hierarchy and add it to the front along with a slash to indicate that it should make a folder. The
template below accomplishes this:
{#genre:subitems(0,1)||/}{title} - {authors}
See The template language (page 161) for more information about templates and the subitems() function.
10.2 XPath tutorial
In this tutorial, you will be given a gentle introduction to XPath
81
, a query language that can be used to select arbitrary
parts of HTML
82
documents in calibre. XPath is a widely used standard, and googling it will yield a ton of information.
This tutorial, however, focuses on using XPath for e-book related tasks like nding chapter headings in an unstructured
HTML document.
Contents
Selecting by tag name (page 159)
Selecting by attributes (page 159)
Selecting by tag content (page 160)
Sample e-book (page 160)
XPath built-in functions (page 160)
81
https://en.wikipedia.org/wiki/XPath
82
https://en.wikipedia.org/wiki/HTML
158 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.2.1 Selecting by tag name
The simplest form of selection is to select tags by name. For example, suppose you want to select all the <h2> tags in a
document. The XPath query for this is simply:
//h:h2 (Selects all <h2> tags)
The prex // means search at any level of the document. Now suppose you want to search for <span> tags that are inside
<a> tags. That can be achieved with:
//h:a/h:span (Selects <span> tags inside <a> tags)
If you want to search for tags at a particular level in the document, change the prex:
/h:body/h:div/h:p (Selects <p> tags that are children of <div> tags that are
children of the <body> tag)
This will match only <p>A very short e-book to demonstrate the use of XPath.</p> in the
Sample e-book (page 160) but not any of the other <p> tags. The h: prex in the above examples is needed to match
XHTML tags. This is because internally, calibre represents all content as XHTML. In XHTML tags have a namespace,
and h: is the namespace prex for HTML tags.
Now suppose you want to select both <h1> and <h2> tags. To do that, we need a XPath construct called predicate. A
predicate is simply a test that is used to select tags. Tests can be arbitrarily powerful and as this tutorial progresses, you
will see more powerful examples. A predicate is created by enclosing the test expression in square brackets:
//*[name()='h1' or name()='h2']
There are several new features in this XPath expression. The rst is the use of the wildcard *. It means match any tag.
Now look at the test expression name()='h1' or name()='h2'. name() is an example of a built-in function. It
simply evaluates to the name of the tag. So by using it, we can select tags whose names are either h1 or h2. Note that the
name() function ignores namespaces so that there is no need for the h: prex. XPath has several useful built-in functions.
A few more will be introduced in this tutorial.
10.2.2 Selecting by attributes
To select tags based on their attributes, the use of predicates is required:
//*[@style] (Select all tags that have a style attribute)
//*[@class="chapter"] (Select all tags that have class="chapter")
//h:h1[@class="bookTitle"] (Select all h1 tags that have class="bookTitle")
Here, the @ operator refers to the attributes of the tag. You can use some of the XPath built-in functions (page 160) to
perform more sophisticated matching on attribute values.
10.2. XPath tutorial 159
calibre User Manual, Release 7.19.0
10.2.3 Selecting by tag content
Using XPath, you can even select tags based on the text they contain. The best way to do this is to use the power of regular
expressions via the built-in function re:test():
//h:h2[re:test(., 'chapter|section', 'i')] (Selects <h2> tags that contain the words
,chapter or
section)
Here the . operator refers to the contents of the tag, just as the @ operator referred to its attributes.
10.2.4 Sample e-book
<html>
<head>
<title>A very short e-book</title>
<meta name="charset" value="utf-8" />
</head>
<body>
<h1 class="bookTitle">A very short e-book</h1>
<p style="text-align:right">Written by Kovid Goyal</p>
<div class="introduction">
<p>A very short e-book to demonstrate the use of XPath.</p>
</div>
<h2 class="chapter">Chapter One</h2>
<p>This is a truly fascinating chapter.</p>
<h2 class="chapter">Chapter Two</h2>
<p>A worthy continuation of a fine tradition.</p>
</body>
</html>
10.2.5 XPath built-in functions
name()
The name of the current tag.
contains()
contains(s1, s2) returns true if s1 contains s2.
re:test()
re:test(src, pattern, flags) returns true if the string src matches the regular expression pattern. A
particularly useful ag is i, it makes matching case insensitive. A good primer on the syntax for regular expressions
can be found at regexp syntax
83
83
https://docs.python.org/library/re.html
160 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.3 The calibre template language
The calibre template language is a calibre-specic language used throughout calibre for tasks such as specifying le paths,
formatting values, and computing the value for user-specied columns. Examples:
Specify the folder structure and le names when saving les from the calibre library to the disk or e-book reader.
Dene rules for adding icons and colors to the calibre book list.
Dene virtual columns that contain data from other columns.
Advanced library searching.
Advanced metadata search and replace.
The language is built around the notion of a template, which species which book metadata to use, computations on that
metadata, and how it is to be formatted.
10.3.1 Basic templates
A basic template consists one or more template expressions. A template expression consists of text
and names in curly brackets ({}) that is replaced by the corresponding metadata from the book being processed. For
example, the default template in calibre used for saving books to device has 4 template expressions:
{author_sort}/{title}/{title} - {authors}
For the book “The Foundation” by “Isaac Asimov” the will become:
Asimov, Isaac/The Foundation/The Foundation - Isaac Asimov
The slashes are not template expressions because they are in between in {}. Such text is left where it appears.
For example, if the template is:
{author_sort} Some Important Text {title}/{title} - {authors}
then for “The Foundation” the template produces:
Asimov, Isaac Some Important Text The Foundation/The Foundation - Isaac Asimov
A template expression can access all the metadata available in calibre, including custom columns (columns you
create yourself), by using a column’s lookup name. To nd the lookup name for a column (sometimes called elds),
hover your mouse over the column header in calibre’s book list. Lookup names for custom columns always begin with
#. For series type columns there is an additional eld named #lookup name_index that is the series index for that
book in the series. For example, if you have a custom series column named #myseries, there will also be a column
named #myseries_index. The standard series column’s index is named series_index.
In addition to the standard column based elds, you also can use:
{formats} - A list of formats available in the calibre library for a book
{identifiers:select(isbn)} - The ISBN of the book
If the metadata for the eld for a given book is not dened then the eld in the template is replaced by the empty string
(''). For example, consider the following template:
{author_sort}/{series}/{title} {series_index}
If Asimov’s book “Second Foundation” is in the series “Foundation” then the template produces:
10.3. The calibre template language 161
calibre User Manual, Release 7.19.0
Asimov, Isaac/Foundation/Second Foundation 3
If a series has not been entered for the book then the template produces:
Asimov, Isaac/Second Foundation
The template processor automatically removes multiple slashes and leading or trailing spaces.
10.3.2 Advanced formatting
In addition to metadata substitution, templates can conditionally include additional text and control how substituted data
is formatted.
Conditionally including text
Sometimes you want text to appear in the output only if a eld is not empty. A common case is series and se-
ries_index where you want either nothing or the two values separated by a hyphen. calibre handles this case using a
special template expression syntax.
For example and using the above Foundation example, assume you want the template to produce Foundation - 3 - Second
Foundation. This template produces that output:
{series} - {series_index} - {title}
However, if a book has no series the template will produce - - the title, which is probably not what you want. Generally,
people want the result be the title without the extraneous hyphens. You can accomplish this using the following template
syntax:
{field:|prefix_text|suffix_text}
This template expression says that if field has the value XXXX then the result will be pre-
x_textXXXXXsux_text. If field is empty (has no value) then the result will be the empty string (nothing) because
the prex and sux are ignored. The prex and sux can contain blanks.
Do not use subtemplates (`{ }`) or functions (see below) in the prex or the sux.
Using this syntax, we can solve the above no-series problem with the template:
{series}{series_index:| - | - }{title}
The hyphens will be included only if the book has a series index, which it has only if it has a series. Continuing the
Foundation example again, the template will produce Foundation - 1 - Second Foundation.
Notes:
You must include the colon after the lookup name if you are using a prex or a sux.
You must either use either no or both | characters. Using one, as in {field:| - }, is not allowed.
It is OK to provide no text for either the prex or the sux, such as in {series:|| - }. The template
{title:||} is the same as {title}.
Formatting
Suppose you want the series_index to be formatted as three digits with leading zeros. This does the trick:
{series_index:0>3s} - Three digits with leading zeros
For trailing zeros, use:
{series_index:0<3s} - Three digits with trailing zeros
162 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
If you use series indices with fractional values, e.g., 1.1, you might want the decimal points to line up. For example, you
might want the indices 1 and 2.5 to appear as 01.00 and 02.50 so that they will sort correctly on a device that does lexical
sorting. To do this, use:
{series_index:0>5.2f} - Five characters consisting of two digits with leading zeros, a decimal point,
then 2 digits after the decimal point.
If you want only the rst two letters of the data, use:
{author_sort:.2} - Only the rst two letters of the author sort name
Much of the calibre template language formatting comes from Python. For more details on the syntax of these advanced
formatting operations see the Python documentation
84
.
10.3.3 Using templates to dene custom columns
Templates can be used to display information that isn’t in calibre metadata, or to display metadata dierently from calibre’s
normal format. For example, you might want to show the ISBN, a eld that calibre does not display. You can accomplish
this creating a custom column with the type Column built from other columns (hereafter called composite columns) and
providing a template to generate the displayed text. The column will display the result of evaluating the template. For
example, to display the ISBN, create the column and enter {identifiers:select(isbn)} in the template box.
To display a column containing the values of two series custom columns, separated by a comma, use {#series1:||,
}{#series2}
.
Composite columns can use any template option, including formatting.
Note: You cannot edit the data displayed in a composite column. Instead you edit the source columns. If you edit a
composite column, for example by double-clicking it, calibre will open the template for editing, not the underlying data.
10.3.4 Templates and plugboards
Plugboards are used for changing the metadata written into books during send-to-device and save-to-disk operations. A
plugboard permits you to specify a template to provide the data to write into the book’s metadata. You can use plugboards
to modify the following elds: authors, author_sort, language, publisher, tags, title, title_sort. This feature helps people
who want to use dierent metadata in books on devices to solve sorting or display issues.
When you create a plugboard, you specify the format and device for which the plugboard is to be used. A special device is
provided, save_to_disk, that is used when saving formats (as opposed to sending them to a device). Once you have
chosen the format and device, you choose the metadata elds to change, providing templates to supply the new values.
These templates are connected to their destination elds, hence the name plugboards. You can of course use composite
columns in these templates.
Plugboards are quite exible and can be written in Single Function Mode, Template Program Mode, General Program
Mode, or Python Template mode.
When a plugboard might apply (Content server, save to disk, or send to device), calibre searches the dened plugboards
to choose the correct one for the given format and device. For example, to nd the appropriate plugboard for an EPUB
book being sent to an ANDROID device, calibre searches the plugboards using the following search order:
a plugboard with an exact match on format and device, e.g., EPUB and ANDROID
a plugboard with an exact match on format and the special any device choice, e.g., EPUB and any device
a plugboard with the special any format choice and an exact match on device, e.g., any format and AN-
DROID
a plugboard with any format and any device
84
https://docs.python.org/3/library/string.html#formatstrings
10.3. The calibre template language 163
calibre User Manual, Release 7.19.0
The tags and authors elds have special treatment, because both of these elds can hold more than one item. A book can
have many tags and many authors. When you specify that one of these two elds is to be changed, the template’s result
is examined to see if more than one item is there. For tags, the result is cut apart wherever calibre nds a comma. For
example, if the template produces the value Thriller, Horror, then the result will be two tags, Thriller and
Horror. There is no way to put a comma in the middle of a tag.
The same thing happens for authors, but using a dierent character for the cut, a & (ampersand) instead of a comma.
For example, if the template produces the value Blogs, Joe&Posts, Susan, then the book will end up with two
authors, Blogs, Joe and Posts, Susan. If the template produces the value Blogs, Joe;Posts, Susan,
then the book will have one author with a rather strange name.
Plugboards aect the metadata written into the book when it is saved to disk or written to the device. Plugboards do not
aect the metadata used by save to disk and send to device to create the le names. Instead, le names are
constructed using the templates entered on the appropriate preferences window.
10.3.5 Using functions in templates - Single Function Mode
Suppose you want to display the value of a eld in upper case when that eld is normally in title case. You can do this
using template functions. For example, to display the title in upper case use the uppercase function, as in {ti-
tle:uppercase()}. To display it in title case, use {title:titlecase()}.
Functions go into the format part of the template, after the : and before the rst | or the closing } if no prex/sux is
used. If you have both a format and a function reference, the function comes after a second :. Functions return the value
of the column specied in the template, suitably modied.
The syntax for using functions is one of:
{lookup_name:function(arguments)}
{lookup_name:format:function(arguments)}
{lookup_name:function(arguments)|prefix|suffix}
{lookup_name:format:function(arguments)|prefix|suffix}
Function names must always be followed by opening and closing parentheses. Some functions require extra values (argu-
ments), and these go inside the parentheses. Arguments are separated by commas. Literal commas (commas as text, not
argument separators) must be preceded by a backslash (\) . The last (or only) argument cannot contain a textual closing
parenthesis.
Functions are evaluated before format specications and the prex/sux. See further down for an example of using both
a format and a function.
Important: If you have programming experience, please note that the syntax in Single Function Mode is not what you
expect. Strings are not quoted and spaces are signicant. All arguments are considered to be constants; there are no
expressions.
Do not use subtemplates (`{ }`) as function arguments. Instead, use Template Program Mode (page 181) and
General Program Mode (page 167).
Some functions require regular expressions. In the template language regular expression matching is case-insensitive.
In the function documentation below, the notation [something]* means that something can be repeated zero or
more times. The notation [something]+ means that the something is repeated one or more times (must exist at
least one time).
The functions intended for use in Single Function Mode are:
capitalize() returns the value with the rst letter upper case and the rest lower case.
contains(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 no match.
164 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
count(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:count(,)}, {authors:count(&)}. Aliases: count(), list_count()
format_number(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 o the leading “{0:” and trailing “}” if
the format template contains only a format. See the template language and the Python documentation
85
for more
examples. Returns the empty string if formatting fails.
human_readable() expects the value to be a number and returns a string representing that number in KB,
MB, GB, etc.
ifempty(text if empty) if the value is not empty then return the value of the eld, otherwise return text
if empty.
in_list(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 pat-
tern 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 dierent values depending on the
item’s value. The patterns are checked in order, and the rst match is returned.
language_strings(localize) return the language names
86
for the language codes
87
passed in as the
value. Example: {languages:language_strings()}. If localize is zero, return the strings in En-
glish. If localize is not zero, return the strings in the language of the current locale. Lang_codes is a
comma-separated list.
list_item(index, separator) interpret the value as a list of items separated by separator, re-
turning the ‘index’th item. The rst 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.
lookup([ pattern, key, ]* else_key) The patterns will be checked against the value in order. If
a pattern matches then the value of the eld named by key is returned. If no pattern matches then the value of the
eld named by else_key is returned. See``switch`` (below).
lowercase() returns the value of the eld in lower case.
rating_to_stars(use_half_stars) Returns the rating 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.
re(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
88
.
select(key) interpret the value as a comma-separated list of items with each item having the form
id:value (the calibre identifier format). The function nds the rst pair with the id equal to key and
returns the corresponding value. If no id matches then the function returns the empty string.
shorten(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 in the
Times of Ivanhoe the result will be Ancient E-anhoe: the rst 9 characters of the title, a -, then the last 5 characters.
85
https://docs.python.org/3/library/string.html#formatstrings
86
https://www.loc.gov/standards/iso639-2/php/code_list.php
87
https://www.loc.gov/standards/iso639-2/php/code_list.php
88
https://docs.python.org/3/library/re.html
10.3. The calibre template language 165
calibre User Manual, Release 7.19.0
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 The Dome would not be changed.
str_in_list(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 dierent 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 rst match is returned.
subitems(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 rst 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(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 rst 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”
swap_around_articles(separator) returns the value with articles moved to the end. 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 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() 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.
switch([pattern, value,]+ else_value) for each pattern, value pair, checks if the value
matches the regular expression pattern and if so returns the associated value. If no pattern matches, then
else_value is returned. You can have as many pattern, value pairs as you wish. The rst match is
returned.
test(text if not empty, text if empty) return text if not empty if the value is not
empty, otherwise return text if empty.
titlecase() returns the value of the eld in title case.
166 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
transliterate() Return a string in a latin alphabet formed by approximating the sound of the words in
the source eld. For example, if the source eld is Фёдор Миха́йлович Достоевский this function returns
Fiodor Mikhailovich Dostoievskii.
uppercase() returns the value of the eld in upper case.
Using functions and formatting in the same template
Suppose you have an integer custom column #myint that you want displayed with leading zeros, as in 003. One way
to do this is to use a format of 0>3s. However, by default if a number (integer or oat) equals zero then the value is
displayed as the empty string so zero values will produce the empty string, not 000. If you want to see 000 values then
you use both the format string and the ifempty function to change the empty value back to a zero. The template would
be:
{#myint:0>3s:ifempty(0)}
Note that you can use the prex and sux as well. If you want the number to appear as [003] or [000], then use the
template:
{#myint:0>3s:ifempty(0)|[|]}
10.3.6 General Program Mode
General Program Mode (GPM) replaces template expressions with a program written in the template language. The syntax
of the language is dened by the following grammar:
program ::= 'program:' expression_list
expression_list ::= top_expression [ ';' top_expression ]*
top_expression ::= or_expression
or_expression ::= and_expression [ '||' and_expression ]*
and_expression ::= not_expression [ '&&' not_expression ]*
not_expression ::= [ '!' not_expression ]* | concatenate_expr
concatenate_expr::= compare_expr [ '&' compare_expr ]*
compare_expr ::= add_sub_expr [ compare_op add_sub_expr ]
compare_op ::= '==' | '!=' | '>=' | '>' | '<=' | '<' | 'in' | 'inlist' |
'==#' | '!=#' | '>=#' | '>#' | '<=#' | '<#'
add_sub_expr ::= times_div_expr [ add_sub_op times_div_expr ]*
add_sub_op ::= '+' | '-'
times_div_expr ::= unary_op_expr [ times_div_op unary_op_expr ]*
times_div_op ::= '*' | '/'
unary_op_expr ::= [ add_sub_op unary_op_expr ]* | expression
expression ::= identifier | constant | function | assignment | field_reference |
if_expr | for_expr | break_expr | continue_expr |
'(' expression_list ')' | function_def
field_reference ::= '$' [ '$' ] [ '#' ] identifier
identifier ::= id_start [ id_rest ]*
id_start ::= letter | underscore
id_rest ::= id_start | digit
constant ::= " string " | ' string ' | number
function ::= identifier '(' expression_list [ ',' expression_list ]* ')'
function_def ::= 'def' identifier '(' top_expression [ ',' top_expression ]* ')' ':
,'
expression_list 'fed'
assignment ::= identifier '=' top_expression
if_expr ::= 'if' condition 'then' expression_list
[ elif_expr ] [ 'else' expression_list ] 'fi'
condition ::= top_expression
(continues on next page)
10.3. The calibre template language 167
calibre User Manual, Release 7.19.0
(continued from previous page)
elif_expr ::= 'elif' condition 'then' expression_list elif_expr | ''
for_expr ::= for_list | for_range
for_list ::= 'for' identifier 'in' list_expr
[ 'separator' separator_expr ] ':' expression_list 'rof'
for_range ::= 'for' identifier 'in' range_expr ':' expression_list 'rof'
range_expr ::= 'range' '(' [ start_expr ',' ] stop_expr
[ ',' step_expr [ ',' limit_expr ] ] ')'
list_expr ::= top_expression
break_expr ::= 'break'
continue_expr ::= 'continue'
separator_expr ::= top_expression
start_expr ::= top_expression
stop_expr ::= top_expression
step_expr ::= top_expression
limit_expr ::= top_expression
Notes:
a top_expression always has a value. The value of an expression_list is the value of the last
top_expression in the list. For example, the value of the expression list 1;2;'foobar';3 is 3.
In a logical context, any non-empty value is True
In a logical context, the empty value is False
Strings and numbers can be used interchangeably. For example, 10 and '10' are the same thing.
Comments are lines starting with a ‘#’ character. Comments beginning later in a line are not supported.
Operator precedence
The operator precedence (order of evaluation) from highest (evaluated rst) to lowest (evaluated last) is:
Function calls, constants, parenthesized expressions, statement expressions, assignment expressions, eld refer-
ences.
Unary plus (+) and minus (-). These operators evaluate right to left.
These and all the other arithmetic operators return integers if the expression results in a fractional part equal to
zero. For example, if an expression returns 3.0 it is changed to 3.
Multiply (*) and divide (/). These operators are associative and evaluate left to right. Use parentheses if you want
to change the order of evaluation.
Add (+) and subtract (-). These operators are associative and evaluate left to right.
Numeric and string comparisons. These operators return '1' if the comparison succeeds, otherwise the empty
string (''). Comparisons are not associative: a < b < c is a syntax error.
String concatenation (&). The & operator returns a string formed by concatenating the left-hand and right-hand
expressions. Example: 'aaa' & 'bbb' returns 'aaabbb'. The operator is associative and evaluates left to
right.
Unary logical not (!). This operator returns '1' if the expression is False (evaluates to the empty string), otherwise
''.
Logical and (&&). This operator returns ‘1’ if both the left-hand and right-hand expressions are True, or the empty
string '' if either is False. It is associative, evaluates left to right, and does short-circuiting
89
.
89
https://chortle.ccsu.edu/java5/Notes/chap40/ch40_2.html
168 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
Logical or (||). This operator returns '1' if either the left-hand or right-hand expression is True, or '' if both
are False. It is associative, evaluates left to right, and does short-circuiting
90
. It is an inclusive or, returning '1' if
both the left- and right-hand expressions are True.
Field references
A field_reference evaluates to the value of the metadata eld named by lookup name that follows the $ or $$.
Using $ is equivalent to using the field() function. Using $$ is equivalent to using the raw_field function.
Examples:
* $authors ==> field('authors')
* $#genre ==> field('#genre')
* $$pubdate ==> raw_field('pubdate')
* $$#my_int ==> raw_field('#my_int')
If expressions
If expressions rst evaluate the condition. If the condition is True (a non-empty value) then the expres-
sion_list in the then clause is evaluated. If it is False then if present the expression_list in the elif or
else clause is evaluated. The elif and else parts are optional. The words if, then, elif, else, and fi are
reserved; you cannot use them as identier names. You can put newlines and white space wherever they make sense.
The condition is a top_expression not an expression_list; semicolons are not allowed. The expres-
sion_lists are semicolon-separated sequences of top_expressions. An if expression returns the result of the
last top_expression in the evaluated expression_list, or the empty string if no expression list was evaluated.
Examples:
* program: if field('series') then 'yes' else 'no' fi
* program:
if field('series') then
a = 'yes';
b = 'no'
else
a = 'no';
b = 'yes'
fi;
strcat(a, '-', b)
Nested if example:
program:
if field('series') then
if check_yes_no(field('#mybool'), '', '', '1') then
'yes'
else
'no'
fi
else
'no series'
fi
As said above, an if produces a value. This means that all the following are equivalent:
* program: if field('series') then 'foo' else 'bar' fi
* program: if field('series') then a = 'foo' else a = 'bar' fi; a
* program: a = if field('series') then 'foo' else 'bar' fi; a
90
https://chortle.ccsu.edu/java5/Notes/chap40/ch40_2.html
10.3. The calibre template language 169
calibre User Manual, Release 7.19.0
As a last example, this program returns the value of the series column if the book has a series, otherwise the value of
the title column:
program: field(if field('series') then 'series' else 'title' fi)
For expressions
The for expression iterates over a list of values, processing them one at a time. The list_expression must evaluate
either to a metadata eld lookup name e.g., tags or #genre, or to a list of values. The range() function (page 179)
(see below) generates a list of numbers. If the result is a valid lookup name then the eld’s value is fetched and the
separator specied for that eld type is used. If the result isn’t a valid lookup name then it is assumed to be a list of values.
The list is assumed to be separated by commas unless the optional keyword separator is supplied, in which case the
list values must be separated by the result of evaluating the separator_expr. A separator cannot be used if the list
is generated by range(). Each value in the list is assigned to the specied variable then the expression_list is
evaluated. You can use break to jump out of the loop, and continue to jump to the beginning of the loop for the
next iteration.
Example: This template removes the rst hierarchical name for each value in Genre (#genre), constructing a list with
the new names:
program:
new_tags = '';
for i in '#genre':
j = re(i, '^.*?\.(.*)$', '\1');
new_tags = list_union(new_tags, j, ',')
rof;
new_tags
If the original Genre is History.Military, Science Fiction.Alternate History, ReadMe then the template returns Military,
Alternate History, ReadMe. You could use this template in calibre’s Edit metadata in bulk  →  Search & replace with
Search for set to template to strip o the rst level of the hierarchy and assign the resulting value to Genre.
Note: the last line in the template, new_tags, isn’t strictly necessary in this case because for returns the value of the
last top_expression in the expression list. The value of an assignment is the value of its expression, so the value of the
for statement is what was assigned to new_tags.
Function denition
If you have code in a template that repeats then you can put that code into a local function. The def keyword starts the
denition. It is followed by the function name, the argument list, then the code in the function. The function denition
ends with the fed keyword.
Arguments are positional. When a function is called the supplied arguments are matched left to right against the dened
parameters, with the value of the argument assigned to the parameter. It is an error to provide more arguments than
dened parameters. Parameters can have default values, such as a = 25. If an argument is not supplied for that
parameter then the default value is used, otherwise the parameter is set to the empty string.
The return statement can be used in a local function.
A function must be dened before it can be used.
Example: This template computes an approximate duration in years, months, and days from a number of days. The
function to_plural() formats the computed values. Note that the example also uses the & operator:
program:
days = 2112;
years = floor(days/360);
months = floor(mod(days, 360)/30);
days = days - ((years*360) + (months * 30));
(continues on next page)
170 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
(continued from previous page)
def to_plural(v, str):
if v == 0 then return '' fi;
return v & ' ' & (if v == 1 then str else str & 's' fi) & ' '
fed;
to_plural(years, 'year') & to_plural(months, 'month') & to_plural(days,'day')
Relational operators
Relational operators return '1' if the comparison is true, otherwise the empty string (‘’).
There are two forms of relational operators: string comparisons and numeric comparisons.
String comparisons do case-insensitive string comparison using lexical order. The supported string comparison operators
are ==, !=, <, <=, >, >=, in, and inlist. For the in operator, the result of the left hand expression is interpreted as
a regular expression pattern. The in operator is True if the value of left-hand regular expression matches the value of
the right hand expression. The inlist operator is true if the left hand regular expression matches any one of the items
in the right hand list where the items in the list are separated by commas. The matches are case-insensitive.
The numeric comparison operators are ==#, !=#, <#, <=#, >#, >=#. The left and right expressions must evaluate to
numeric values with two exceptions: both the string value “None” (undened eld) and the empty string evaluate to the
value zero.
Examples:
program: field('series') == 'foo' returns '1' if the book’s series is ‘foo’, otherwise ''.
program: 'f.o' in field('series') returns '1' if the book’s series matches the regular expression
f.o (e.g., foo, O Onyx, etc.), otherwise ''.
program: 'science' inlist field('#genre') returns '1' if any of the book’s genres match the
regular expression science, e.g., Science, History of Science, Science Fiction etc., otherwise ''.
program: '^science$' inlist field('#genre') returns '1' if any of the book’s genres exactly
match the regular expression ^science$, e.g., Science. The genres History of Science and Science Fiction don’t
match. If there isn’t a match then returns ''.
program: if field('series') != 'foo' then 'bar' else 'mumble' fi returns 'bar'
if the book’s series is not foo. Otherwise it returns 'mumble'.
program: if field('series') == 'foo' || field('series') == '1632' then 'yes'
else 'no' fi returns 'yes' if series is either 'foo' or '1632', otherwise 'no'.
program: if '^(foo|1632)$' in field('series') then 'yes' else 'no' fi returns
'yes' if series is either 'foo' or '1632', otherwise 'no'.
program: if 11 > 2 then 'yes' else 'no' fi returns 'no' because the > operator does a
lexical comparison.
program: if 11 ># 2 then 'yes' else 'no' fi returns 'yes' because the ># operator does a
numeric comparison.
Additional available functions
The following functions are available in addition to those described in Single Function Mode (page 164).
In GPM the functions described in Single Function Mode all require an additional rst parameter specifying the value to
operate upon. All parameters are expression_lists (see the grammar above).
add(x [, y]*) returns the sum of its arguments. Throws an exception if an argument is not a number. In
most cases you can use the + operator instead of this function.
10.3. The calibre template language 171
calibre User Manual, Release 7.19.0
and(value [, value]*) returns the string “1” if all values are not empty, otherwise returns the empty
string. You can have as many values as you want. In most cases you can use the && operator instead of this function.
One reason not to replace and with && is if short-circuiting can change the results because of side eects. For
example, and(a='',b=5) will always do both assignments, where the && operator won’t do the second.
assign(id, val) assigns val to id, then returns val. id must be an identier, not an expression. In
most cases you can use the = operator instead of this function.
approximate_formats() return a comma-separated list of formats associated with the book. There is no
guarantee that the list is correct, although it probably is. This and other zero-parameter functions can be called in
Template Program Mode (see below) using the template {:'approximate_formats()'}. Note that result-
ing format names are always uppercase, as in EPUB. The approximate_formats() function is signicantly
faster than the formats_... functions discussed below.
author_links(val_separator, pair_separator) returns a string containing a list of authors and
those authors’ link values in the form:
author1 val_separator author1_link pair_separator author2 val_separator author2_
,link etc.
An author is separated from its link value by the val_separator string with no added spaces. au-
thor:linkvalue pairs are separated by the pair_separator string argument with no added spaces. It
is up to you to choose separator strings that do not occur in author names or links. An author is included even if
the author link is empty.
author_sorts(val_separator) returns a string containing a list of author’s sort values for the authors
of the book. The sort is the one in the author metadata information (dierent from the author_sort in books). The
returned list has the form author sort 1 val_separator author sort 2 etc. with no added spaces.
The author sort values in this list are in the same order as the authors of the book. If you want spaces around
val_separator then include them in the val_separator string.
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 par-
ticularly 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 al-
low_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 nd all series with only one book:
1) Dene a stored template (using Preferences → Advanced → Template functions) named se-
ries_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 rst time the template runs (the rst 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.
2) Use the stored template in a template search:
172 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
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 require-
ment to escape quotes in search expressions.
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 al-
low_template_database_functions_in_composites is set to True. It can be used only in the GUI.
booksize() returns the value of the calibre ‘size’ eld. Returns ‘’ if there are no formats.
check_yes_no(field_name, is_undefined, is_false, is_true) checks if the value of
the yes/no eld named by the lookup name field_name is one of the values specied by the parameters, re-
turning '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 eld #bool is either True or undened
(neither True nor False).
More than one of is_undefined, is_false, or is_true can be set to 1.
ceiling(x) returns the smallest integer greater than or equal to x. Throws an exception if x is not a number.
character(character_name) returns the character named by character_name. For example, char-
acter('newline') returns a newline character ('\n'). The supported character names are newline, re-
turn, tab, and backslash.
cmp(x, y, lt, eq, gt) compares x and y after converting both to numbers. Returns lt if x <# y,
eq
if
x ==# y
, otherwise
gt
. This function can usually be replaced with one of the numeric compare operators
(==#, <#, >#, etc).
connected_device_name(storage_location_key) if a device is connected then return the de-
vice 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(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 dierent uuid. The
storage_location_key location names are 'main', 'carda' and 'cardb'. This function works only
in the GUI.
current_library_name() return the last name on the path to the current calibre library.
current_library_path() return the full path to the current calibre library.
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: cur-
rent_virtual_library_name(). This function works only in the GUI.
date_arithmetic(date, calc_spec, fmt) Calculate a new date from date using calc_spec.
Return the new date formatted according to optional fmt: if not supplied then the result will be in ISO format. The
calc_spec is a string formed by concatenating pairs of vW (valueWhat) where v is a possibly-negative number
and W is one of the following letters:
s: add v seconds to date
m: add v minutes to date
h: add v hours to date
10.3. The calibre template language 173
calibre User Manual, Release 7.19.0
d: add v days to date
w: add v weeks to date
y: add v years to date, where a year is 365 days.
Example: '1s3d-1m' will add 1 second, add 3 days, and subtract 1 minute from date.
days_between(date1, date2) 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.
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.
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 (page 181), 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 prexes and suxes (the |prex|sux syntax) cannot
be used in the argument to this function when using Template Program Mode (page 181).
extra_file_size(file_name) – returns the size in bytes of the extra le file_name in the
book’s data/ folder if it exists, otherwise -1. See also the functions has_extra_files(), ex-
tra_file_names() and extra_file_modtime(). This function can be used only in the GUI.
extra_file_modtime(file_name, format_string) returns the modication time of the extra
le 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 oating 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.
extra_file_names(sep [, pattern]) returns a sep-separated list of extra les in the book’s data/
folder. If the optional parameter pattern, a regular expression, is supplied then the list is ltered to les that
match pattern. The pattern match is case insensitive. See also the functions has_extra_files(), ex-
tra_file_modtime() and extra_file_size(). This function can be used only in the GUI.
field(lookup_name) returns the value of the metadata eld with lookup name lookup_name.
field_exists(field_name) checks if a eld (column) with the lookup name field_name exists,
returning '1' if so and the empty string if not.
finish_formatting(val, fmt, prefix, suffix) apply the format, prex, and sux to a 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')
)
174 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
first_matching_cmp(val, [ cmp, result, ]* else_result) compares val < cmp in
sequence, returning the associated result for the rst 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 rst value of 16 returns "giant".
first_non_empty(value [, value]*) returns the rst 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.
floor(x) returns the largest integer less than or equal to x. Throws an exception if x is not a number.
format_date(val, format_string) format the value, which must be a date string, using the for-
mat_string, returning a string. The formatting codes are:
d : the day as number without a leading zero (1 to 31)
dd : the day as number with a leading zero (01 to 31)
ddd : the abbreviated localized day name (e.g. “Mon” to “Sun”).
dddd : the long localized day name (e.g. “Monday” to “Sunday”).
M : the month as number without a leading zero (1 to 12).
MM : the month as number with a leading zero (01 to 12)
MMM : the abbreviated localized month name (e.g. “Jan” to “Dec”).
MMMM : the long localized month name (e.g. “January” to “December”).
yy : the year as two digit number (00 to 99).
yyyy : the year as four digit number.
h : the hours without a leading 0 (0 to 11 or 0 to 23, depending on am/pm)
hh : the hours with a leading 0 (00 to 11 or 00 to 23, depending on am/pm)
m : the minutes without a leading 0 (0 to 59)
mm : the minutes with a leading 0 (00 to 59)
s : the seconds without a leading 0 (0 to 59)
ss : the seconds with a leading 0 (00 to 59)
ap : use a 12-hour clock instead of a 24-hour clock, with ‘ap’ replaced by the localized string for am or pm.
AP : use a 12-hour clock instead of a 24-hour clock, with ‘AP’ replaced by the localized string for AM or
PM.
iso : the date with time and timezone. Must be the only format present.
to_number : convert the date & time into a oating point number (a timestamp)
from_number : convert a oating point number (a timestamp) into an iso formatted date. If you want a
dierent date format then add the desired formatting string after from_number and a colon (:). Example:
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 tweaks to contain MMMM. In this case, instead of using the field() function as in:
format_date(field('pubdate'), 'yyyy')
10.3. The calibre template language 175
calibre User Manual, Release 7.19.0
use the raw_field() function as in:
format_date(raw_field('pubdate'), 'yyyy')
format_date_field(field_name, format_string) format the value in the eld field_name,
which must be the lookup name of date eld, 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
eld (column). 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')
formats_modtimes(date_format_string) return a comma-separated list of colon-separated items
FMT:DATE representing modication times for the formats of a book. The date_format_string parameter
species how the date is to be formatted. See the format_date() function for details. You can use the select
function to get the modication time for a specic format. Note that format names are always uppercase, as in
EPUB.
formats_paths() return a comma-separated list of colon-separated items FMT:PATH giving the full path
to the formats of a book. You can use the select function to get the path for a specic format. Note that format
names are always uppercase, as in EPUB.
formats_sizes() return a comma-separated list of colon-separated FMT:SIZE items giving the sizes in
bytes of the formats of a book. You can use the select function to get the size for a specic format. Note that
format names are always uppercase, as in EPUB.
fractional_part(x) returns the value after the decimal point. For example, fractional_part(3.
14) returns 0.14. Throws an exception if x is not a number.
get_link(field_name, field_value) fetch the link for eld 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
get_note(field_name, field_value, plain_text) fetch the note for eld ‘eld_name’ with
value ‘eld_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:
176 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
program:
get_note('authors', 'Isaac Asimov', 1)
has_cover() return 'Yes' if the book has a cover, otherwise the empty string.
has_extra_files([pattern]) returns the count of extra les, otherwise ‘’ (the empty string). If the op-
tional parameter pattern (a regular expression) is supplied then the list is ltered to les that match pattern be-
fore the les 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.
identifier_in_list(val, id_name [, found_val, not_found_val]) treat val as a list
of identiers separated by commas. An identier 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 rst case matches if there is any
identier matching that id_name. The second case matches if id_name matches an identier and the regexp matches
the identier’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 ('').
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 dierent colors/icons according to the mode.
Example:
if is_dark_mode() then 'dark.png' else 'light.png' fi
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(lang_strings) return the language codes
91
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.
list_contains(value, separator, [ pattern, found_val, ]* not_found_val)
(Alias of in_list) Interpreting the value as a list of items separated by separator, evaluate the pattern
against each value in the list. If the pattern matches any value then return found_val, otherwise return
not_found_val. The pattern and found_value can be repeated as many times as desired, permitting
returning dierent values depending on the search. The patterns are checked in order. The rst match is returned.
Aliases: in_list(), list_contains()
list_count(value, separator) interprets value as a list of items separated by separator, re-
turning the count of items in the list. Aliases: count(), list_count()
list_count_matching(list, pattern, separator) interprets list as a list of items separated
by separator, returning the number of items in the list that match the regular expression pattern. Aliases:
list_count_matching(), count_matching()
list_difference(list1, list2, separator) return a list made by removing from list1 any
item found in list2 using a case-insensitive comparison. The items in list1 and list2 are separated by
separator, as are the items in the returned list.
list_equals(list1, sep1, list2, sep2, yes_val, no_val) return yes_val if list1
and list2 contain the same items, otherwise return no_val. The items are determined by splitting each list using
the appropriate separator character (sep1 or sep2). The order of items in the lists is not relevant. The comparison
is case-insensitive.
list_intersection(list1, list2, separator) 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
91
https://www.loc.gov/standards/iso639-2/php/code_list.php
10.3. The calibre template language 177
calibre User Manual, Release 7.19.0
by separator, as are the items in the returned list.
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 eld like publisher that is single-valued, eectively 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 dier 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 rst letter of the genre, i.e. the genre “Fiction”
becomes “Genre: F”. The following will do that:
program:
list_join('#@#', $authors, '&', list_re($#genre, ',', '^(.).*$', 'Genre: \1'),
,',')
list_re(src_list, separator, include_re, opt_replace) Construct a list by rst sep-
arating src_list into items using the separator character. For each item in the list, check if it matches
include_re. If it does then add it to the list to be returned. If opt_replace is not the empty string then
apply the replacement before adding the item to the returned list.
list_re_group(src_list, separator, include_re, search_re [, tem-
plate_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, separator) return a list made by removing duplicate items in
list. If items dier 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, direction, separator) return list sorted using a case-insensitive lexical
sort. If direction is zero, list is sorted ascending, otherwise descending. The list items are separated by
separator, as are the items in the returned list.
list_split(list_val, sep, id_prefix) 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
rst 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
178 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
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 dier 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()
mod(x, y) returns the floor of the remainder of x / y. Throws an exception if either x or y is not a
number.
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.
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.
ondevice() return the string 'Yes' if ondevice is set, otherwise return the empty string.
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 eects.
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 rst
argument.
range(start, stop, step, limit) returns a list of numbers generated by looping over the range
specied by the parameters start, stop, and step, with a maximum length of limit. The rst 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 species 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)
raw_field(lookup_name [, optional_default]) – returns the metadata eld named by
lookup_name without applying any formatting. It evaluates and returns the optional second argument op-
tional_default if the eld’s value is undened (None).
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.
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 corre-
sponding template. In Template Program Mode (page 181), 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 rst word:
program: re_group(field('series'), "(\S* )(.*)", "{$:uppercase()}", "{$}")'}
round(x) returns the nearest integer to x. Throws an exception if x is not a number.
series_sort() returns the series sort value.
10.3. The calibre template language 179
calibre User Manual, Release 7.19.0
strcat(a [, b]*) can take any number of arguments. Returns a string formed by concatenating all the
arguments.
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. Prexes can be empty. Returns
string1 even if string1 is longer than max. You can pass as many prefix, string pairs as you wish.
strcmp(x, y, lt, eq, gt) does a case-insensitive lexical comparison of x and y. Returns lt if x <
y, eq if x == y, otherwise gt. This function can often be replaced by one of the lexical comparison operators
(==, >, <, etc.)
strcmpcase(x, y, lt, eq, gt) does a case-sensitive lexical comparison of x and y. Returns lt if x
< y, eq if x == y, otherwise gt.
Note: This is NOT the default behavior used by calibre, for example, in the lexical comparison operators (==, >,
<, etc.). This function could cause unexpected results, preferably use strcmp() whenever possible.
strlen(value) Returns the length of the string value.
substr(str, start, end)
returns the
start
’th through the
end
’th characters of
str
. The rst
character in str is the zero’th character. If end is negative, then it indicates that many characters counting from
the right. If end is zero, then it indicates the last character. For example, substr('12345', 1, 0) returns
'2345', and substr('12345', 1, -1) returns '234'.
subtract(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.
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.
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
92
date/time format.
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.
to_hex(val) returns the string val encoded in hex. This is useful when constructing calibre URLs.
urls_from_identifiers(identifiers, sort_results) given a comma-separated list of
identifiers, where an identier is a colon-separated pair of values (id_name:id_value), returns a
comma-separated list of HTML URLs generated from the identiers. The list not sorted if sort_results is 0 (char-
acter or number), otherwise it is sorted alphabetically by the identier name. The URLs are generated in the same
way as the built-in identiers column when shown in Book details.
92
https://en.wikipedia.org/wiki/ISO_8601
180 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.3.7 More complex programs in template expressions - Template Program Mode
Template Program Mode (TPM) is a blend of General Program Mode (page 167) and Single Function Mode (page 164).
TPM diers from Single Function Mode in that it permits writing template expressions that refer to other metadata elds,
use nested functions, modify variables, and do arithmetic. It diers from
General Program Mode
in that the template is
contained between { and } characters and doesn’t begin with the word program:. The program portion of the template
is a General Program Mode expression list.
Example: assume you want a template to show the series for a book if it has one, otherwise show the value of a custom
eld #genre. You cannot do this in the Single Function Mode (page 164) because you cannot make reference to another
metadata eld within a template expression. In TPM you can, as the following expression demonstrates:
{#series:'ifempty($, field('#genre'))'}
The example shows several things:
TPM is used if the expression begins with :' and ends with '}. Anything else is assumed to be in Single Function
Mode (page 164).
the variable $ stands for the eld named in the template: the expression is operating upon, #series in this case.
functions must be given all their arguments. There is no default value. For example, the standard built-in functions
must be given an additional initial parameter indicating the source eld.
white space is ignored and can be used anywhere within the expression.
constant strings are enclosed in matching quotes, either ' or ".
All the functions listed under Single Function Mode and General Program Mode can be used in TPM.
In TPM, using { and } characters in string literals can lead to errors or unexpected results because they confuse the
template processor. It tries to treat them as template expression boundaries, not characters. In some but not all cases you
can replace a { with [[ and a } with ]]. Generally, if your program contains { and } characters then you should use
General Program Mode.
As with General Program Mode, for functions documented under Single Function Mode (page 164) you must supply the
value the function is to act upon as the rst parameter in addition to the documented parameters. In TPM you can use $
to access the value specied by the lookup name for the template expression.
10.3.8 Python Template Mode
Python Template Mode (PTM) lets you write templates using native python and the calibre API
93
. The database API
will be of most use; further discussion is beyond the scope of this manual. PTM templates are faster and can do more
complicated operations but you must know how to write code in python using the calibre API.
A PTM template begins with:
python:
def evaluate(book, context):
# book is a calibre metadata object
# context is an instance of calibre.utils.formatter.PythonTemplateContext,
# which currently contains the following attributes:
# db: a calibre legacy database object.
# globals: the template global variable dictionary.
# arguments: is a list of arguments if the template is called by a GPM template,
,otherwise None.
# funcs: used to call Built-in/User functions and Stored GPM/Python templates.
(continues on next page)
93
https://manual.calibre-ebook.com/develop.html#api-documentation-for-various-parts-of-calibre
10.3. The calibre template language 181
calibre User Manual, Release 7.19.0
(continued from previous page)
# Example: context.funcs.list_re_group()
# your Python code goes here
return 'a string'
You can add the above text to your template using the context menu, usually accessed with a right click. The comments
are not signicant and can be removed. You must use python indenting.
The context object supports str(context) that returns a string of the context’s contents, and context.
attributes that returns a list of the attribute names in the context.
The context.funcs attribute allows calling Built-in and User template functions, and Stored GPM/Python templates,
so that you can execute them directly in your code. The functions are retrieved using their names. If the name conicts
with a Python keyword, add an underscore to the end of the name. Examples:
context.funcs.list_re_group()
context.funcs.assert_()
Here is an example of a PTM template that produces a list of all the authors for a series. The list is stored in a Column built
from other columns, behaves like tags. It shows in Book details and has the on separate lines checked (in Preferences → Look
& feel → Book details). That option requires the list to be comma-separated. To satisfy that requirement the template
converts commas in author names to semicolons then builds a comma-separated list of authors. The authors are then
sorted, which is why the template uses author_sort.
python:
def evaluate(book, context):
if book.series is None:
return ''
db = context.db.new_api
ans = set()
# Get the list of books in the series
ids = db.search(f'series:"={book.series}"', '')
if ids:
# Get all the author_sort values for the books in the series
author_sorts = (v for v in db.all_field_for('author_sort', ids).values())
# Add the names to the result set, removing duplicates
for aus in author_sorts:
ans.update(v.strip() for v in aus.split('&'))
# Make a sorted comma-separated string from the result set
return ', '.join(v.replace(',', ';') for v in sorted(ans))
The output in Book details looks like this:
182 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.3.9 Stored templates
Both General Program Mode (page 167) and Python Template Mode (page 181) support saving templates and call-
ing those templates from another template, much like calling stored functions. You save templates using Prefer-
ences → Advanced → Template functions. More information is provided in that dialog. You call a template the same
way you call a function, passing positional arguments if desired. An argument can be any expression. Examples of
calling a template, assuming the stored template is named foo:
foo() call the template passing no arguments.
foo(a, b) call the template passing the values of the two variables a and b.
foo(if field('series') then field('series_index') else 0 fi) if the book has a
series then pass the series_index, otherwise pass the value 0.
In GPM you retrieve the arguments passed in the call to the stored template using the arguments function. It both
declares and initializes local variables, eectively parameters. The variables are positional; they get the value of the
parameter given in the call in the same position. If the corresponding parameter is not provided in the call then argu-
ments assigns that variable the provided default value. If there is no default value then the variable is set to the empty
string. For example, the following arguments function declares 2 variables, key, alternate:
arguments(key, alternate='series')
Examples, again assuming the stored template is named foo:
foo('#myseries') argument key is assigned the value 'myseries' and the argument alternate is
assigned the default value 'series'.
foo('series', '#genre') the variable key is assigned the value 'series' and the variable alter-
nate is assigned the value '#genre'.
10.3. The calibre template language 183
calibre User Manual, Release 7.19.0
foo() the variable key is assigned the empty string and the variable alternate is assigned the value 'se-
ries'.
In PTM the arguments are passed in the arguments parameter, which is a list of strings. There isn’t any way to specify
default values. You must check the length of the arguments list to be sure that the number of arguments is what you
expect.
An easy way to test stored templates is using the Template tester dialog. For ease of access give it a keyboard
shortcut in Preferences → Advanced → Keyboard shortcuts → Template tester. Giving the Stored templates dialog
a shortcut will help switching more rapidly between the tester and editing the stored template’s source code.
10.3.10 Providing additional information to templates
A developer can choose to pass additional information to the template processor, such as application-specic book meta-
data or information about what the processor is being asked to do. A template can access this information and use it
during the evaluation.
Developer: how to pass additional information
The additional information is a Python dictionary containing pairs variable_name: variable_value where
the values must be strings. The template can access the dictionary, creating template local variables named vari-
able_name containing the value variable_value. The user cannot change the name so it is best to use names that
won’t collide with other template local variables, for example by prexing the name with an underscore.
This dictionary is passed to the template processor (the formatter) using the named parameter
global_vars=your_dict. The full method signature is:
def safe_format(self, fmt, kwargs, error_value, book,
column_name=None, template_cache=None,
strip_results=True, template_functions=None,
global_vars={})
Template writer: how to access the additional information
You access the additional information (the globals dictionary) in a template using the template function:
globals(id[=expression] [, id[=expression]]*)
where id is any legal variable name. This function checks whether the additional information provided by the developer
contains the name. If it does then the function assigns the provided value to a template local variable with that name. If
the name is not in the additional information and if an expression is provided, the expression is evaluated and
the result is assigned to the local variable. If neither a value nor an expression is provided, the function assigns the empty
string ('') to the local variable.
A template can set a value in the globals dictionary using the template function:
set_globals(id[=expression] [, id[=expression]]*)
This function sets the globals dictionary key:value pair id:value where value is the value of the template local
variable id. If that local variable doesn’t exist then value is set to the result of evaluating expression.
184 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.3.11 Notes on the dierence between modes
The three program modes, Single Function Mode (page 164) (SFM), Template Program Mode (page 181) (TPM), and Gen-
eral Program Mode (page 167) (GPM), work dierently. SFM is intended to be ‘simple’ so it hides a lot of programming
language bits.
Dierences:
In SFM the value of the column is always passed as an ‘invisible’ rst argument to a function included in the
template.
SFM doesn’t support the dierence between variables and strings; all values are strings.
The following SFM template returns either the series name or the string “no series”:
{series:ifempty(no series)}
The equivalent template in TPM is
{series:'ifempty($, 'no series')'}
The equivalent template in GPM is:
program: ifempty(field('series'), 'no series')
The rst argument to ifempty is the value of the eld series. The second argument is the string no series.
In SFM the rst argument, the value of the eld, is automatically passed (the invisible argument).
Several template functions, for example booksize() and current_library_name(), take no arguments.
Because of the ‘invisible argument’ you cannot use these functions in SFM.
Nested functions, where a function calls another function to compute an argument, cannot be used in SFM. For
example this template, intended to return the rst 5 characters of the series value uppercased, won’t work in SFM:
{series:uppercase(substr(0,5))}
TPM and GPM support nested functions. The above template in TPM would be:
{series:'uppercase(substr($, 0,5))'}
In GPM it would be:
program: uppercase(substr(field('series'), 0,5))
As noted in the above Template Program Mode (page 181) section, using { and } characters in TPM string literals
can lead to errors or unexpected results because they confuse the template processor. It tries to treat them as
template boundaries, not characters. In some but not all cases you can replace a { with [[ and a } with ]].
Generally, if your program contains { and } characters then you should use General Program Mode.
10.3. The calibre template language 185
calibre User Manual, Release 7.19.0
10.3.12 User-dened Python template functions
You can add your own Python functions to the template processor. Such functions can be used in any of the three template
programming modes. The functions are added by going to Preferences  →  Advanced  →  Template functions. Instructions
are shown in that dialog.
10.3.13 Special notes for save/send templates
Special processing is applied when a template is used in a save to disk or send to device template. The values of the elds
are cleaned, replacing characters that are special to le systems with underscores, including slashes. This means that eld
text cannot be used to create folders. However, slashes are not changed in prex or sux strings, so slashes in these strings
will cause folders to be created. Because of this, you can create variable-depth folder structure.
For example, assume we want the folder structure series/series_index - title, with the caveat that if series does not exist,
then the title should be in the top folder. The template to do this is:
{series:||/}{series_index:|| - }{title}
The slash and the hyphen appear only if series is not empty.
The lookup function lets us do even fancier processing. For example, assume that if a book has a series, then we want
the folder structure series/series index - title.fmt. If the book does not have a series then we want the folder structure
genre/author_sort/title.fmt. If the book has no genre then we want to use ‘Unknown’. We want two completely dierent
paths, depending on the value of series.
To accomplish this, we:
1. Create a composite eld (give it lookup name #aa) containing {series}/{series_index} - {title}.
If the series is not empty, then this template will produce series/series_index - title.
2. Create a composite eld (give it lookup name #bb) containing {#genre:ifempty(Unknown)}/
{author_sort}/{title}. This template produces genre/author_sort/title, where an empty genre is replaced
with Unknown.
3. Set the save template to
{series:lookup(.,#aa,#bb)}
. This template chooses composite eld
#aa
if
series is not empty and composite eld #bb if series is empty. We therefore have two completely dierent save
paths, depending on whether or not series is empty.
10.3.14 Tips
Use the Template Tester to test templates. Add the tester to the context menu for books in the library and/or give
it a keyboard shortcut.
Templates can use other templates by referencing composite columns built with the desired template. Alternatively,
you can use Stored Templates.
In a plugboard, you can set a eld to empty (or whatever is equivalent to empty) by using the special template {}.
This template will always evaluate to an empty string.
The technique described above to show numbers even if they have a zero value works with the standard eld
series_index.
186 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.3.15 Function reference
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 insucient. The
functions are arranged in logical groups by type.
Arithmetic (page 191)
add(x [, y]*) (page 191)
ceiling(x) (page 191)
divide(x, y) (page 191)
oor(x) (page 191)
fractional_part(x) (page 191)
mod(x) (page 191)
multiply(x [, y]*) (page 191)
round(x) (page 192)
subtract(x, y) (page 192)
Boolean (page 192)
and(value [, value]*) (page 192)
not(value) (page 192)
or(value [, value]*) (page 192)
Date functions (page 192)
date_arithmetic(date, calc_spec, fmt) (page 192)
days_between(date1, date2) (page 193)
today() (page 193)
Formatting values (page 193)
nish_formatting(val, fmt, prex, sux) (page 193)
format_date(val, format_string) (page 193)
format_date_eld(eld_name, format_string) (page 194)
format_number(v, template) (page 194)
human_readable(v) (page 194)
rating_to_stars(value, use_half_stars) (page 194)
urls_from_identiers(identiers, sort_results) (page 194)
Get values from metadata (page 194)
annotation_count() (page 194)
approximate_formats() (page 195)
10.3. The calibre template language 187
calibre User Manual, Release 7.19.0
author_links(val_separator, pair_separator) (page 195)
author_sorts(val_separator) (page 195)
booksize() (page 195)
connected_device_name(storage_location) (page 195)
connected_device_uuid(storage_location) (page 196)
current_library_name() (page 196)
current_library_path() (page 196)
current_virtual_library_name() (page 196)
eld(lookup_name) (page 196)
formats_modtimes(date_format) (page 196)
formats_paths() (page 197)
formats_sizes() (page 197)
has_cover() (page 197)
is_marked() (page 197)
language_codes(lang_strings) (page 197)
language_strings(lang_codes, localize) (page 197)
ondevice() (page 198)
raw_eld(lookup_name [, optional_default]) (page 198)
raw_list(lookup_name, separator) (page 198)
series_sort() (page 198)
user_categories() (page 198)
virtual_libraries() (page 198)
If-then-else (page 199)
check_yes_no(eld_name, is_undened, is_false, is_true) (page 199)
contains(val, pattern, text if match, text if not match) (page 199)
eld_exists(eld_name) (page 199)
ifempty(val, text if empty) (page 199)
test(val, text if not empty, text if empty) (page 199)
Iterating over values (page 199)
rst_non_empty(value [, value]*) (page 199)
lookup(val, [pattern, eld,]+ else_eld) (page 200)
switch(val, [pattern, value,]+ else_value) (page 200)
switch_if([test_expression, value_expression,]+ else_expression) (page 200)
List lookup (page 200)
identier_in_list(val, id_name [, found_val, not_found_val]) (page 200)
188 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
in_list(val, separator, [ pattern, found_val, ]+ not_found_val) (page 200)
list_item(val, index, separator) (page 201)
select(val, key) (page 201)
str_in_list(val, separator, [string, found_val, ]+ not_found_val) (page 201)
List manipulation (page 201)
count(val, separator) (page 201)
list_count_matching(list, pattern, separator) (page 201)
list_dierence(list1, list2, separator) (page 202)
list_equals(list1, sep1, list2, sep2, yes_val, no_val) (page 202)
list_intersection(list1, list2, separator) (page 202)
list_join(with_separator, list1, separator1 [, list2, separator2]*) (page 202)
list_re(src_list, separator, include_re, opt_replace) (page 203)
list_re_group(src_list, separator, include_re, search_re [, group_template]+) (page 203)
list_remove_duplicates(list, separator) (page 203)
list_sort(list, direction, separator) (page 203)
list_split(list_val, sep, id_prex) (page 203)
list_union(list1, list2, separator) (page 203)
range(start, stop, step, limit) (page 204)
subitems(val, start_index, end_index) (page 204)
sublist(val, start_index, end_index, separator) (page 204)
Other (page 204)
arguments(id[=expression] [, id[=expression]]*) (page 204)
assign(id, val) (page 205)
globals(id[=expression] [, id[=expression]]*) (page 205)
print(a[, b]*) (page 205)
Recursion (page 205)
eval(template) (page 205)
template(x) (page 205)
Relational (page 206)
cmp(x, y, lt, eq, gt) (page 206)
rst_matching_cmp(val, [cmp1, result1,]+, else_result) (page 206)
strcmp(x, y, lt, eq, gt) (page 206)
strcmpcase(x, y, lt, eq, gt) (page 206)
String case changes (page 206)
capitalize(val) (page 206)
10.3. The calibre template language 189
calibre User Manual, Release 7.19.0
lowercase(val) (page 207)
titlecase(val) (page 207)
uppercase(val) (page 207)
String manipulation (page 207)
character(character_name) (page 207)
re(val, pattern, replacement) (page 207)
re_group(val, pattern [, template_for_group]*) (page 207)
shorten(val, left chars, middle text, right chars) (page 208)
strcat(a [, b]*) (page 208)
strcat_max(max, string1 [, prex2, string2]*) (page 208)
strlen(a) (page 208)
substr(str, start, end) (page 208)
swap_around_articles(val, separator) (page 208)
swap_around_comma(val) (page 209)
to_hex(val) (page 209)
transliterate(a) (page 209)
Template database functions (page 209)
book_count(query, use_vl) (page 209)
book_values(column, query, sep, use_vl) (page 209)
extra_le_modtime(le_name, format_string) (page 209)
extra_le_names(sep [, pattern]) (page 210)
extra_le_size(le_name) (page 210)
get_link(eld_name, eld_value) (page 210)
get_note(eld_name, eld_value, plain_text) (page 210)
has_extra_les([pattern]) (page 210)
has_note(eld_name, eld_value) (page 210)
other (page 211)
is_dark_mode() (page 211)
set_globals(id[=expression] [, id[=expression]]*) (page 211)
API of the Metadata objects (page 211)
190 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
Arithmetic
add(x [, y]*)
class calibre.utils.formatter_functions.BuiltinAdd
add(x [, y]*) returns the sum of its arguments. Throws an exception if an argument is not a number. This function
can often be replaced with the + operator.
ceiling(x)
class calibre.utils.formatter_functions.BuiltinCeiling
ceiling(x) returns the smallest integer greater than or equal to x. Throws an exception if x is not a number.
divide(x, y)
class calibre.utils.formatter_functions.BuiltinDivide
divide(x, y) returns x / y. Throws an exception if either x or y are not numbers. This function can often be
replaced with the / operator.
oor(x)
class calibre.utils.formatter_functions.BuiltinFloor
oor(x) returns the largest integer less than or equal to x. Throws an exception if x is not a number.
fractional_part(x)
class calibre.utils.formatter_functions.BuiltinFractionalPart
fractional_part(x) returns the value after the decimal point. For example, fractional_part(3.14) returns 0.14.
Throws an exception if x is not a number.
mod(x)
class calibre.utils.formatter_functions.BuiltinMod
mod(x) returns oor(remainder of x / y). Throws an exception if either x or y is not a number.
multiply(x [, y]*)
class calibre.utils.formatter_functions.BuiltinMultiply
multiply(x [, y]*) returns the product of its arguments. Throws an exception if any argument is not a number.
This function can often be replaced with the * operator.
10.3. The calibre template language 191
calibre User Manual, Release 7.19.0
round(x)
class calibre.utils.formatter_functions.BuiltinRound
round(x) returns the nearest integer to x. Throws an exception if x is not a number.
subtract(x, y)
class
calibre.utils.formatter_functions.
BuiltinSubtract
subtract(x, y) returns x - y. Throws an exception if either x or y are not numbers. This function can often be
replaced with the - operator.
Boolean
and(value [, value]*)
class calibre.utils.formatter_functions.BuiltinAnd
and(value [, value]*) returns the string “1” if all values are not empty, otherwise returns the empty string. This
function works well with test or rst_non_empty. You can have as many values as you want. In many cases the
&& operator can replace this function.
not(value)
class calibre.utils.formatter_functions.BuiltinNot
not(value) returns the string “1” if the value is empty, otherwise returns the empty string. This function works
well with test or rst_non_empty. In many cases the ! operator can replace this function.
or(value [, value]*)
class calibre.utils.formatter_functions.BuiltinOr
or(value [, value]*) returns the string “1” if any value is not empty, otherwise returns the empty string. This
function works well with test or rst_non_empty. You can have as many values as you want. In many cases the ||
operator can replace this function.
Date functions
date_arithmetic(date, calc_spec, fmt)
class calibre.utils.formatter_functions.BuiltinDateArithmetic
date_arithmetic(date, calc_spec, fmt) Calculate a new date from ‘date’ using ‘calc_spec’. Return the new date
formatted according to optional ‘fmt’: if not supplied then the result will be in iso format. The calc_spec is a string
formed by concatenating pairs of ‘vW’ (valueWhat) where ‘v’ is a possibly-negative number and W is one of the
following letters: s: add ‘v’ seconds to ‘date’ m: add ‘v’ minutes to ‘date’ h: add ‘v’ hours to ‘date’ d: add ‘v’ days to
‘date’ w: add ‘v’ weeks to ‘date’ y: add ‘v’ years to ‘date’, where a year is 365 days. Example: ‘1s3d-1m’ will add 1
second, add 3 days, and subtract 1 minute from ‘date’.
192 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
days_between(date1, date2)
class calibre.utils.formatter_functions.BuiltinDaysBetween
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()
class calibre.utils.formatter_functions.BuiltinToday
today() return a date string for today. 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 format.
Formatting values
nish_formatting(val, fmt, prex, sux)
class calibre.utils.formatter_functions.BuiltinFinishFormatting
nish_formatting(val, fmt, prex, sux) apply the format, prex, and sux to a value in the same way as done
in a template like {series_index:05.2f| - |- }. For example, the following program produces the same output as the
above template: program: nish_formatting(eld(“series_index”), “05.2f”, - “, - “)
format_date(val, format_string)
class calibre.utils.formatter_functions.BuiltinFormatDate
format_date(val, format_string) format the value, which must be a date, using the format_string, returning a
string. The formatting codes are: d : the day as number without a leading zero (1 to 31) dd : the day as number
with a leading zero (01 to 31) ddd : the abbreviated localized day name (e.g. “Mon” to “Sun”). dddd : the long
localized day name (e.g. “Monday” to “Sunday”). M : the month as number without a leading zero (1 to 12). MM
: the month as number with a leading zero (01 to 12) MMM : the abbreviated localized month name (e.g. “Jan”
to “Dec”). MMMM : the long localized month name (e.g. “January” to “December”). yy : the year as two digit
number (00 to 99). yyyy : the year as four digit number. h : the hours without a leading 0 (0 to 11 or 0 to 23,
depending on am/pm) hh : the hours with a leading 0 (00 to 11 or 00 to 23, depending on am/pm) m : the minutes
without a leading 0 (0 to 59) mm : the minutes with a leading 0 (00 to 59) s : the seconds without a leading 0
(0 to 59) ss : the seconds with a leading 0 (00 to 59) ap : use a 12-hour clock instead of a 24-hour clock, with
“ap” replaced by the localized string for am or pm AP : use a 12-hour clock instead of a 24-hour clock, with “AP”
replaced by the localized string for AM or PM iso : the date with time and timezone. Must be the only format
present to_number: the date as a oating point number from_number[:fmt]: format the timestamp using fmt if
present otherwise iso
10.3. The calibre template language 193
calibre User Manual, Release 7.19.0
format_date_eld(eld_name, format_string)
class calibre.utils.formatter_functions.BuiltinFormatDateField
format_date_eld(eld_name, format_string) format the value in the eld ‘eld_name’, which must be the lookup
name of date eld, 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 eld (column). It can’t be used
for computed dates or dates in string variables. Example: format_date_eld(‘pubdate’, ‘yyyy.MM.dd’)
format_number(v, template)
class calibre.utils.formatter_functions.BuiltinFormatNumber
format_number(v, template) format the number v using a Python formatting template such as “{0:5.2f}” or
“{0:,d}” or “${0:5,.2f}”. The eld_name part of the template must be a 0 (zero) (the “{0:” in the above examples).
See the template language and Python documentation for more examples. You can leave o the leading “{0:” and
trailing “}” if the template contains only a format. Returns the empty string if formatting fails.
human_readable(v)
class calibre.utils.formatter_functions.BuiltinHumanReadable
human_readable(v) return a string representing the number v in KB, MB, GB, etc.
rating_to_stars(value, use_half_stars)
class calibre.utils.formatter_functions.BuiltinRatingToStars
rating_to_stars(value, use_half_stars) Returns the rating as string of star characters. The value is a number
between 0 and 5. Set use_half_stars to 1 if you want half star characters for custom ratings columns that support
non-integer ratings, for example 2.5.
urls_from_identiers(identiers, sort_results)
class calibre.utils.formatter_functions.BuiltinUrlsFromIdentifiers
urls_from_identiers(identiers, sort_results) given a comma-separated list of identiers, where an identier is
a colon-separated pair of values (name:id_value), returns a comma-separated list of HTML URLs generated from
the identiers. The list not sorted if sort_results is 0 (character or number), otherwise it is sorted alphabetically
by the identier name. The URLs are generated in the same way as the built-in identiers column when shown in
Book details.
Get values from metadata
annotation_count()
class calibre.utils.formatter_functions.BuiltinAnnotationCount
annotation_count() return the total number of annotations of all types attached to the current book. This function
works only in the GUI.
194 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
approximate_formats()
class calibre.utils.formatter_functions.BuiltinApproximateFormats
approximate_formats() return a comma-separated list of formats that at one point were associated with the book.
There is no guarantee that this list is correct, although it probably is. This function can be called in template program
mode using the template “{:’approximate_formats()’}”. Note that format names are always uppercase, as in EPUB.
This function works only in the GUI. If you want to use these values in save-to-disk or send-to-device templates
then you must make a custom “Column built from other columns”, use the function in that column’s template, and
use that column’s value in your save/send templates
author_links(val_separator, pair_separator)
class calibre.utils.formatter_functions.BuiltinAuthorLinks
author_links(val_separator, pair_separator) returns a string containing a list of authors and that author’s link
values in the form author1 val_separator author1link pair_separator author2 val_separator author2link etc. An
author is separated from its link value by the val_separator string with no added spaces. author:linkvalue pairs are
separated by the pair_separator string argument with no added spaces. It is up to you to choose separator strings
that do not occur in author names or links. An author is included even if the author link is empty.
author_sorts(val_separator)
class calibre.utils.formatter_functions.BuiltinAuthorSorts
author_sorts(val_separator) returns a string containing a list of author’s sort values for the authors of the book.
The sort is the one in the author metadata (dierent from the author_sort in books). The returned list has the form
author sort 1 val_separator author sort 2 etc. The author sort values in this list are in the same order as the authors
of the book. If you want spaces around val_separator then include them in the separator string
booksize()
class calibre.utils.formatter_functions.BuiltinBooksize
booksize() return value of the size eld. This function works only in the GUI. If you want to use this value in
save-to-disk or send-to-device templates then you must make a custom “Column built from other columns”, use
the function in that column’s template, and use that column’s value in your save/send templates
connected_device_name(storage_location)
class calibre.utils.formatter_functions.BuiltinConnectedDeviceName
connected_device_name(storage_location) if a device is connected then return the device name, otherwise return
the empty string. Each storage location on a device can have a dierent name. The location names are ‘main’,
‘carda’ and ‘cardb’. This function works only in the GUI.
10.3. The calibre template language 195
calibre User Manual, Release 7.19.0
connected_device_uuid(storage_location)
class calibre.utils.formatter_functions.BuiltinConnectedDeviceUUID
connected_device_uuid(storage_location) if a device is connected then return the device uuid (unique id), other-
wise return the empty string. Each storage location on a device has a dierent uuid. The location names are ‘main’,
‘carda’ and ‘cardb’. This function works only in the GUI.
current_library_name()
class calibre.utils.formatter_functions.BuiltinCurrentLibraryName
current_library_name() return the last name on the path to the current calibre library. This function can be called
in template program mode using the template “{:’current_library_name()’}”.
current_library_path()
class calibre.utils.formatter_functions.BuiltinCurrentLibraryPath
current_library_path() return the path to the current calibre library. This function can be called in template
program mode using the template “{:’current_library_path()’}”.
current_virtual_library_name()
class calibre.utils.formatter_functions.BuiltinCurrentVirtualLibraryName
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()”.
eld(lookup_name)
class calibre.utils.formatter_functions.BuiltinField
eld(lookup_name) returns the metadata eld named by lookup_name
formats_modtimes(date_format)
class calibre.utils.formatter_functions.BuiltinFormatsModtimes
formats_modtimes(date_format) return a comma-separated list of colon-separated items representing modica-
tion times for the formats of a book. The date_format parameter species how the date is to be formatted. See the
format_date function for details. You can use the select function to get the mod time for a specic format. Note
that format names are always uppercase, as in EPUB.
196 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
formats_paths()
class calibre.utils.formatter_functions.BuiltinFormatsPaths
formats_paths() return a comma-separated list of colon-separated items representing full path to the formats of
a book. You can use the select function to get the path for a specic format. Note that format names are always
uppercase, as in EPUB.
formats_sizes()
class calibre.utils.formatter_functions.BuiltinFormatsSizes
formats_sizes() return a comma-separated list of colon-separated items representing sizes in bytes of the formats
of a book. You can use the select function to get the size for a specic format. Note that format names are always
uppercase, as in EPUB.
has_cover()
class calibre.utils.formatter_functions.BuiltinHasCover
has_cover() return Yes if the book has a cover, otherwise return the empty string
is_marked()
class calibre.utils.formatter_functions.BuiltinIsMarked
is_marked() check whether the book is ‘marked’ in calibre. If it is then return the value of the mark, either ‘true’
or the comma-separated list of named marks. Returns ‘’ if the book is not marked.
language_codes(lang_strings)
class calibre.utils.formatter_functions.BuiltinLanguageCodes
language_codes(lang_strings) return the language codes for the strings passed in lang_strings. The strings must
be in the language of the current locale. Lang_strings is a comma-separated list.
language_strings(lang_codes, localize)
class calibre.utils.formatter_functions.BuiltinLanguageStrings
language_strings(lang_codes, localize) return the strings for the language codes passed in lang_codes. If localize
is zero, return the strings in English. If localize is not zero, return the strings in the language of the current locale.
Lang_codes is a comma-separated list.
10.3. The calibre template language 197
calibre User Manual, Release 7.19.0
ondevice()
class calibre.utils.formatter_functions.BuiltinOndevice
ondevice() return Yes if ondevice is set, otherwise return the empty string. This function works only in the GUI.
If you want to use this value in save-to-disk or send-to-device templates then you must make a custom “Column
built from other columns”, use the function in that column’s template, and use that column’s value in your save/send
templates
raw_eld(lookup_name [, optional_default])
class calibre.utils.formatter_functions.BuiltinRawField
raw_eld(lookup_name [, optional_default]) returns the metadata eld named by lookup_name without applying
any formatting. It evaluates and returns the optional second argument ‘default’ if the eld is undened (‘None’).
raw_list(lookup_name, separator)
class calibre.utils.formatter_functions.BuiltinRawList
raw_list(lookup_name, separator) returns the metadata list named by lookup_name without applying any format-
ting or sorting and with items separated by separator.
series_sort()
class calibre.utils.formatter_functions.BuiltinSeriesSort
series_sort() return the series sort value
user_categories()
class calibre.utils.formatter_functions.BuiltinUserCategories
user_categories() return a comma-separated list of the user categories that contain this book. This function works
only in the GUI. If you want to use these values in save-to-disk or send-to-device templates then you must make
a custom “Column built from other columns”, use the function in that column’s template, and use that column’s
value in your save/send templates
virtual_libraries()
class calibre.utils.formatter_functions.BuiltinVirtualLibraries
virtual_libraries() return a comma-separated list of Virtual libraries that contain this book. This function works
only in the GUI. If you want to use these values in save-to-disk or send-to-device templates then you must make
a custom “Column built from other columns”, use the function in that column’s template, and use that column’s
value in your save/send templates
198 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
If-then-else
check_yes_no(eld_name, is_undened, is_false, is_true)
class calibre.utils.formatter_functions.BuiltinCheckYesNo
check_yes_no(eld_name, is_undened, is_false, is_true) checks the value of the yes/no eld named by the
lookup key eld_name for a value specied by the parameters, returning “yes” if a match is found, otherwise
returning an empty string. Set the parameter is_undened, 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 eld “#bool”
is either undened (neither True nor False) or True. More than one of is_undened, is_false, or is_true can be set
to 1. This function is usually used by the test() or is_empty() functions.
contains(val, pattern, text if match, text if not match)
class calibre.utils.formatter_functions.BuiltinContains
contains(val, pattern, text if match, text if not match) checks if val contains matches for the regular expression
pattern. Returns text if match if matches are found, otherwise it returns text if no match
eld_exists(eld_name)
class calibre.utils.formatter_functions.BuiltinFieldExists
eld_exists(eld_name) checks if a eld (column) named eld_name exists, returning ‘1’ if so and ‘’ if not.
ifempty(val, text if empty)
class calibre.utils.formatter_functions.BuiltinIfempty
ifempty(val, text if empty) return val if val is not empty, otherwise return text if empty
test(val, text if not empty, text if empty)
class calibre.utils.formatter_functions.BuiltinTest
test(val, text if not empty, text if empty) return text if not empty if val is not empty, otherwise return text if empty
Iterating over values
rst_non_empty(value [, value]*)
class calibre.utils.formatter_functions.BuiltinFirstNonEmpty
rst_non_empty(value [, value]*) returns the rst 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.
10.3. The calibre template language 199
calibre User Manual, Release 7.19.0
lookup(val, [pattern, eld,]+ else_eld)
class calibre.utils.formatter_functions.BuiltinLookup
lookup(val, [pattern, eld,]+ else_eld) like switch, except the arguments are eld (metadata) names, not text.
The value of the appropriate eld will be fetched and used. Note that because composite columns are elds, you
can use this function in one composite eld to use the value of some other composite eld. This is extremely useful
when constructing variable save paths
switch(val, [pattern, value,]+ else_value)
class calibre.utils.formatter_functions.BuiltinSwitch
switch(val, [pattern, value,]+ else_value) for each pattern, value pair, checks if val matches the regular expression
pattern and if so, returns that value. If no pattern matches, then else_value is returned. You can have as many
pattern, value pairs as you want
switch_if([test_expression, value_expression,]+ else_expression)
class calibre.utils.formatter_functions.BuiltinSwitchIf
switch_if([test_expression, value_expression,]+ else_expression) for each “test_expression, value_expression”
pair, checks if test_expression is True (non-empty) and if so returns the result of value_expression. If no
test_expression is True then the result of else_expression is returned. You can have as many “test_expression,
value_expression” pairs as you want.
List lookup
identier_in_list(val, id_name [, found_val, not_found_val])
class calibre.utils.formatter_functions.BuiltinIdentifierInList
identier_in_list(val, id_name [, found_val, not_found_val]) treat val as a list of identiers separated by commas.
An identier 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 rst case matches if there is any identier matching that id_name. The
second case matches if id_name matches an identier and the regexp matches the identier’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 identier:value pair, otherwise
the empty string.
in_list(val, separator, [ pattern, found_val, ]+ not_found_val)
class calibre.utils.formatter_functions.BuiltinInList
in_list(val, separator, [ pattern, found_val, ]+ not_found_val) treating val as a list of items separated by separator,
if the pattern matches any of the list values then return found_val.If the pattern matches no list value then return
not_found_val. The pattern and found_value pairs can be repeated as many times as desired. The patterns are
checked in order. The found_val for the rst match is returned. Aliases: in_list(), list_contains()
200 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
list_item(val, index, separator)
class calibre.utils.formatter_functions.BuiltinListitem
list_item(val, index, separator) interpret the value as a list of items separated by separator, returning the index`th
item. The rst item is number zero. The last item can be returned using `list_item(-1,separator). If the item is not in
the list, then the empty value is returned. The separator has the same meaning as in the count function.
select(val, key)
class calibre.utils.formatter_functions.BuiltinSelect
select(val, key) interpret the value as a comma-separated list of items, with the items being “id:value”. Find the
pair with the id equal to key, and return the corresponding value. Returns the empty string if no match is found.
str_in_list(val, separator, [string, found_val, ]+ not_found_val)
class calibre.utils.formatter_functions.BuiltinStrInList
str_in_list(val, separator, [string, found_val, ]+ not_found_val) treating val as a list of items separated by separa-
tor, if the string matches any of the list values then return found_val.If the string matches no list value then return
not_found_val. The comparison is exact match (not contains) and is case insensitive. The string and found_value
pairs can be repeated as many times as desired. The patterns are checked in order. The found_val for the rst
match is returned.
List manipulation
count(val, separator)
class calibre.utils.formatter_functions.BuiltinCount
count(val, separator) interprets the value as a list of items separated by separator, returning the number of items
in the list. Most lists use a comma as the separator, but authors uses an ampersand. Examples: {tags:count(,)},
{authors:count(&)}. Aliases: count(), list_count()
list_count_matching(list, pattern, separator)
class calibre.utils.formatter_functions.BuiltinListCountMatching
list_count_matching(list, pattern, separator) interprets ‘list’ as a list of items separated by ‘separator’, return-
ing the number of items in the list that match the regular expression ‘pattern’. Aliases: list_count_matching(),
count_matching()
10.3. The calibre template language 201
calibre User Manual, Release 7.19.0
list_dierence(list1, list2, separator)
class calibre.utils.formatter_functions.BuiltinListDifference
list_dierence(list1, list2, separator) return a list made by removing from list1 any item found in list2, using a
case-insensitive comparison. The items in list1 and list2 are separated by separator, as are the items in the returned
list.
list_equals(list1, sep1, list2, sep2, yes_val, no_val)
class calibre.utils.formatter_functions.BuiltinListEquals
list_equals(list1, sep1, list2, sep2, yes_val, no_val) return yes_val if list1 and list2 contain the same items, other-
wise return no_val. The items are determined by splitting each list using the appropriate separator character (sep1
or sep2). The order of items in the lists is not relevant. The comparison is case insensitive.
list_intersection(list1, list2, separator)
class calibre.utils.formatter_functions.BuiltinListIntersection
list_intersection(list1, list2, separator) return a list made by removing from list1 any item not found in list2,
using a case-insensitive comparison. The items in list1 and list2 are separated by separator, as are the items in the
returned list.
list_join(with_separator, list1, separator1 [, list2, separator2]*)
class calibre.utils.formatter_functions.BuiltinListJoin
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 eld like publisher that
is single-valued, eectively 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 dier only in letter case then the last is used.
All separators can be more than one character. Example:
program:
list_join(‘#@#’, $authors, ‘&’, $tags, ‘,’)
You can use list_join on the results of previous calls to list_join as follows:
program:
a = list_join(‘#@#’, $authors, ‘&’, $tags, ‘,’); b = list_join(‘#@#’, a, ‘#@#’, $#genre, ‘,’, $#people,
‘&’)
You can use expressions to generate a list. For example, assume you want items for authors and #genre,
but with the genre changed to the word ‘Genre: followed by the rst 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’), ‘,’)
202 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
list_re(src_list, separator, include_re, opt_replace)
class calibre.utils.formatter_functions.BuiltinListRe
list_re(src_list, separator, include_re, opt_replace) Construct a list by rst separating src_list into items using the
separator character. For each item in the list, check if it matches include_re. If it does, then add it to the list to be
returned. If opt_replace is not the empty string, then apply the replacement before adding the item to the returned
list.
list_re_group(src_list, separator, include_re, search_re [, group_template]+)
class calibre.utils.formatter_functions.BuiltinListReGroup
list_re_group(src_list, separator, include_re, search_re [, group_template]+) Like list_re except replacements
are not optional. It uses re_group(list_item, search_re, group_template, …) when doing the replacements on the
resulting list.
list_remove_duplicates(list, separator)
class calibre.utils.formatter_functions.BuiltinListRemoveDuplicates
list_remove_duplicates(list, separator) return a list made by removing duplicate items in the source list. If items
dier only in case, the last of them is returned. The items in source list are separated by separator, as are the items
in the returned list.
list_sort(list, direction, separator)
class calibre.utils.formatter_functions.BuiltinListSort
list_sort(list, direction, separator) return list sorted using a case-insensitive sort. If direction is zero, the list is
sorted ascending, otherwise descending. The list items are separated by separator, as are the items in the returned
list.
list_split(list_val, sep, id_prex)
class calibre.utils.formatter_functions.BuiltinListSplit
list_split(list_val, sep, id_prex) splits the list_val into separate values using ‘sep’, then assigns the values to
variables named ‘id_prex_N’ where N is the position of the value in the list. The rst item has position 0 (zero).
The function returns the last element in the list. Example: split(‘one:two:foo’, ‘:’, ‘var’) is equivalent to var_0 = ‘one’;
var_1 = ‘two’; var_2 = ‘foo’.
list_union(list1, list2, separator)
class calibre.utils.formatter_functions.BuiltinListUnion
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 dier in case, the one in list1 is used. The items in list1 and
list2 are separated by separator, as are the items in the returned list. Aliases: list_union(), merge_lists()
10.3. The calibre template language 203
calibre User Manual, Release 7.19.0
range(start, stop, step, limit)
class calibre.utils.formatter_functions.BuiltinRange
range(start, stop, step, limit) returns a list of numbers generated by looping over the range specied by the
parameters start, stop, and step, with a maximum length of limit. The rst value produced is ‘start’. Subsequent
values next_v are current_v+step. The loop continues while next_v < stop assuming step is positive, otherwise
while next_v > stop. An empty list is produced if start fails the test: start>=stop if step is positive. The limit sets
the maximum length of the list and has a default of 1000. The parameters start, step, and limit are optional. Calling
range() with one argument species stop. Two arguments specify start and stop. Three arguments specify start,
stop, and step. Four arguments specify start, stop, step and limit. Examples: range(5) -> ‘0,1,2,3,4’. range(0,5)
-> ‘0,1,2,3,4’. range(-1,5) -> ‘-1,0,1,2,3,4’. range(1,5) -> ‘1,2,3,4’. range(1,5,2) -> ‘1,3’. range(1,5,2,5) -> ‘1,3’.
range(1,5,2,1) -> error(limit exceeded).
subitems(val, start_index, end_index)
class calibre.utils.formatter_functions.BuiltinSubitems
subitems(val, start_index, end_index) This function is used to break apart lists of items such as genres. It interprets
the value as a comma-separated list of items, where each item is a period-separated list. Returns a new list made
by rst nding all the period-separated items, then for each such item extracting the start_index to the end_index
components, then combining the results back together. The rst component in a period-separated list has an index
of zero. If an index is negative, then it counts from the end of the list. As a special case, an end_index of zero is
assumed to be the length of the list. Example using basic template mode and assuming a #genre value of “A.B.C”:
{#genre:subitems(0,1)} returns “A”. {#genre:subitems(0,2)} returns “A.B”. {#genre:subitems(1,0)} returns “B.C”.
Assuming a #genre value of “A.B.C, D.E.F”, {#genre:subitems(0,1)} returns “A, D”. {#genre:subitems(0,2)} re-
turns “A.B, D.E”
sublist(val, start_index, end_index, separator)
class calibre.utils.formatter_functions.BuiltinSublist
sublist(val, start_index, end_index, separator) interpret the value as a list of items separated by separator, returning
a new list made from the start_index to the end_index item. The rst item is number zero. If an index is negative,
then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the
list. Examples using basic template mode and assuming that the tags column (which is comma-separated) contains
“A, B, C”: {tags:sublist(0,1,\,)} returns “A”. {tags:sublist(-1,0,\,)} returns “C”. {tags:sublist(0,-1,\,)} returns “A,
B”.
Other
arguments(id[=expression] [, id[=expression]]*)
class calibre.utils.formatter_functions.BuiltinArguments
arguments(id[=expression] [, id[=expression]]*) Used in a stored template to retrieve the arguments passed in
the call. It both declares and initializes local variables, eectively parameters. The variables are positional; they get
the value of the parameter given in the call in the same position. If the corresponding parameter is not provided in
the call then arguments assigns that variable the provided default value. If there is no default value then the variable
is set to the empty string.
204 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
assign(id, val)
class calibre.utils.formatter_functions.BuiltinAssign
assign(id, val) assigns val to id, then returns val. id must be an identier, not an expression. This function can
often be replaced with the = operator.
globals(id[=expression] [, id[=expression]]*)
class calibre.utils.formatter_functions.BuiltinGlobals
globals(id[=expression] [, id[=expression]]*) Retrieves “global variables” that can be passed into the formatter.
It both declares and initializes local variables with the names of the global variables passed in. If the corresponding
variable is not provided in the passed-in globals then it assigns that variable the provided default value. If there is
no default value then the variable is set to the empty string.
print(a[, b]*)
class calibre.utils.formatter_functions.BuiltinPrint
print(a[, b]*) prints the arguments to standard output. Unless you start calibre from the command line (calibre-
debug -g), the output will go to a black hole.
Recursion
eval(template)
class calibre.utils.formatter_functions.BuiltinEval
eval(template) evaluates the template, passing the local variables (those ‘assign’ed to) instead of the book metadata.
This permits using the template processor to construct complex results from local variables. Because the { and }
characters are special, you must use [[ for the { character and ]] for the } character; they are converted automatically.
Note also that prexes and suxes (the |prex|sux syntax) cannot be used in the argument to this function when
using template program mode.
template(x)
class calibre.utils.formatter_functions.BuiltinTemplate
template(x) evaluates x as a template. The evaluation is done in its own context, meaning that variables are not
shared between the caller and the template evaluation. Because the { and } characters are special, you must use [[ for
the { character and ]] for the } character; they are converted automatically. For example, template(‘[[title_sort]]’)
will evaluate the template {title_sort} and return its value. Note also that prexes and suxes (the |prex|sux
syntax) cannot be used in the argument to this function when using template program mode.
10.3. The calibre template language 205
calibre User Manual, Release 7.19.0
Relational
cmp(x, y, lt, eq, gt)
class calibre.utils.formatter_functions.BuiltinCmp
cmp(x, y, lt, eq, gt) compares x and y after converting both to numbers. Returns lt if x < y. Returns eq if x == y.
Otherwise returns gt. In many cases the numeric comparison operators (>#, <#, ==# etc) can replace this function.
rst_matching_cmp(val, [cmp1, result1,]+, else_result)
class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp
rst_matching_cmp(val, [cmp1, result1,]+, else_result) compares “val < cmpN” in sequence, returning re-
sultN for the rst comparison that succeeds. Returns else_result if no comparison succeeds. Example:
rst_matching_cmp(10,5,”small”,10,”middle”,15,”large”,”giant”) returns “large”. The same example with a rst
value of 16 returns “giant”.
strcmp(x, y, lt, eq, gt)
class calibre.utils.formatter_functions.BuiltinStrcmp
strcmp(x, y, lt, eq, gt) does a case-insensitive comparison of x and y as strings. Returns lt if x < y. Returns eq
if x == y. Otherwise returns gt. In many cases the lexical comparison operators (>, <, == etc) can replace this
function.
strcmpcase(x, y, lt, eq, gt)
class calibre.utils.formatter_functions.BuiltinStrcmpcase
strcmpcase(x, y, lt, eq, gt) does a case-sensitive comparison of x and y as strings. Returns lt if x < y. Returns
eq if x == y. Otherwise returns gt. Note: This is NOT the default behavior used by calibre, for example, in the
lexical comparison operators (==, >, <, etc.). This function could cause unexpected results, preferably use strcmp()
whenever possible.
String case changes
capitalize(val)
class calibre.utils.formatter_functions.BuiltinCapitalize
capitalize(val) return val capitalized
206 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
lowercase(val)
class calibre.utils.formatter_functions.BuiltinLowercase
lowercase(val) return val in lower case
titlecase(val)
class
calibre.utils.formatter_functions.
BuiltinTitlecase
titlecase(val) return val in title case
uppercase(val)
class calibre.utils.formatter_functions.BuiltinUppercase
uppercase(val) return val in upper case
String manipulation
character(character_name)
class calibre.utils.formatter_functions.BuiltinCharacter
character(character_name) returns the character named by character_name. For example, character(‘newline’)
returns a newline character (’n’). The supported character names are ‘newline’, ‘return’, ‘tab’, and ‘backslash’.
re(val, pattern, replacement)
class calibre.utils.formatter_functions.BuiltinRe
re(val, pattern, replacement) return val after applying the regular expression. All instances of pattern are replaced
with replacement. As in all of calibre, these are Python-compatible regular expressions
re_group(val, pattern [, template_for_group]*)
class calibre.utils.formatter_functions.BuiltinReGroup
re_group(val, pattern [, template_for_group]*) return a string made by applying the regular expression pattern to
the val and replacing each matched instance with the string computed by replacing each matched group by the value
returned by the corresponding template. The original matched value for the group is available as $. In template
program mode, like for the template and the eval functions, you use [[ for { and ]] for }. The following example in
template program mode looks for series with more than one word and uppercases the rst word: {series:’re_group($,
“(S* )(.*)”, “[[$:uppercase()]]”, “[[$]]”)’}
10.3. The calibre template language 207
calibre User Manual, Release 7.19.0
shorten(val, left chars, middle text, right chars)
class calibre.utils.formatter_functions.BuiltinShorten
shorten(val, left chars, middle text, right chars) Return a shortened version of val, consisting of left chars characters
from the beginning of val, followed by middle text, followed by right chars characters from the end of the string.
Left chars and right chars must be integers. For example, assume the title of the book is Ancient English Laws in
the Times of Ivanhoe
, and you want it to t in a space of at most 15 characters. If you use {title:shorten(9,-,5)},
the result will be Ancient E-anhoe. If the eld’s length is less than left chars + right chars + the length of middle
text, then the eld will be used intact. For example, the title The Dome would not be changed.
strcat(a [, b]*)
class calibre.utils.formatter_functions.BuiltinStrcat
strcat(a [, b]*) can take any number of arguments. Returns the string formed by concatenating all the arguments
strcat_max(max, string1 [, prex2, string2]*)
class calibre.utils.formatter_functions.BuiltinStrcatMax
strcat_max(max, string1 [, prex2, string2]*) Returns a string formed by concatenating the arguments. The
returned value is initialized to string1. Prex, string pairs are added to the end of the value as long as the resulting
string length is less than max. String1 is returned even if string1 is longer than max. You can pass as many prex,
string pairs as you wish.
strlen(a)
class calibre.utils.formatter_functions.BuiltinStrlen
strlen(a) Returns the length of the string passed as the argument
substr(str, start, end)
class calibre.utils.formatter_functions.BuiltinSubstr
substr(str, start, end) returns the start’th through the end’th characters of str. The rst character in str is the zero’th
character. If end is negative, then it indicates that many characters counting from the right. If end is zero, then
it indicates the last character. For example, substr(‘12345’, 1, 0) returns ‘2345’, and substr(‘12345’, 1, -1) returns
‘234’.
swap_around_articles(val, separator)
class calibre.utils.formatter_functions.BuiltinSwapAroundArticles
swap_around_articles(val, separator) returns the val with articles moved to the end. The value can be a list, in
which case each member of the list is processed. If the value is a list then you must provide the list value separator.
If no separator is provided then the value is treated as being a single value, not a list.
208 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
swap_around_comma(val)
class calibre.utils.formatter_functions.BuiltinSwapAroundComma
swap_around_comma(val) 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, the function returns val unchanged
to_hex(val)
class calibre.utils.formatter_functions.BuiltinToHex
to_hex(val) returns the string encoded in hex. This is useful when constructing calibre URLs.
transliterate(a)
class calibre.utils.formatter_functions.BuiltinTransliterate
transliterate(a) Returns a string in a latin alphabet formed by approximating the sound of the words in the source
string. For example, if the source is “Фёдор Миха́йлович Достоевский” the function returns “Fiodor Mikhailovich
Dostoievskii”.
Template database functions
book_count(query, use_vl)
class calibre.utils.formatter_functions.BuiltinBookCount
book_count(query, use_vl) returns the count of books found by searching for query. If use_vl is 0 (zero) then
virtual libraries are ignored. This function can be used only in the GUI.
book_values(column, query, sep, use_vl)
class calibre.utils.formatter_functions.BuiltinBookValues
book_values(column, query, sep, use_vl) returns a list of the values contained in the column “column”, separated
by “sep”, in the books found by searching for “query”. If use_vl is 0 (zero) then virtual libraries are ignored. This
function can be used only in the GUI.
extra_le_modtime(le_name, format_string)
class calibre.utils.formatter_functions.BuiltinExtraFileModtime
extra_le_modtime(le_name, format_string) returns the modication time of the extra le ‘le_name’ in the
book’s ‘data/’ folder if it exists, otherwise -1.0. The modtime is formatted according to ‘format_string’ (see for-
mat_date()). If ‘format_string’ is empty, returns the modtime as the oating point number of seconds since the
epoch. The epoch is OS dependent. This function can be used only in the GUI.
10.3. The calibre template language 209
calibre User Manual, Release 7.19.0
extra_le_names(sep [, pattern])
class calibre.utils.formatter_functions.BuiltinExtraFileNames
extra_le_names(sep [, pattern]) returns a sep-separated list of extra les in the book’s ‘data/’ folder. If the
optional parameter ‘pattern’, a regular expression, is supplied then the list is ltered to les that match pattern. The
pattern match is case insensitive. This function can be used only in the GUI.
extra_le_size(le_name)
class calibre.utils.formatter_functions.BuiltinExtraFileSize
extra_le_size(le_name) returns the size in bytes of the extra le ‘le_name’ in the book’s ‘data/’ folder if it
exists, otherwise -1.This function can be used only in the GUI.
get_link(eld_name, eld_value)
class calibre.utils.formatter_functions.BuiltinGetLink
get_link(eld_name, eld_value) fetch the link for eld ‘eld_name’ with value ‘eld_value’. If there is no attached
link, return ‘’. Example: get_link(‘tags’, ‘Fiction’) returns the link attached to the tag ‘Fiction’.
get_note(eld_name, eld_value, plain_text)
class calibre.utils.formatter_functions.BuiltinGetNote
get_note(eld_name, eld_value, plain_text) fetch the note for eld ‘eld_name’ with value ‘eld_value’. If
‘plain_text’ is empty, return the note’s HTML including images. If ‘plain_text’ is 1 (or ‘1’), return the note’s plain
text. If the note doesn’t exist, return the empty string in both cases. Example: get_note(‘tags’, ‘Fiction’, ‘’) returns
the HTML of the note attached to the tag ‘Fiction’.
has_extra_les([pattern])
class calibre.utils.formatter_functions.BuiltinHasExtraFiles
has_extra_les([pattern]) returns the count of extra les, otherwise ‘’ (the empty string). If the optional parameter
‘pattern’ (a regular expression) is supplied then the list is ltered to les that match pattern before the les are
counted. The pattern match is case insensitive. This function can be used only in the GUI.
has_note(eld_name, eld_value)
class calibre.utils.formatter_functions.BuiltinHasNote
has_note(eld_name, eld_value) return ‘1’ if the value ‘eld_value’ in the eld ‘eld_name’ has an attached note,
‘’ otherwise. Example: has_note(‘tags’, ‘Fiction’) returns ‘1’ if the tag ‘ction’ has an attached note, ‘’ otherwise.
210 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
other
is_dark_mode()
class calibre.utils.formatter_functions.BuiltinIsDarkMode
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 dierent colors/icons according to the mode. Example: if
is_dark_mode() then ‘dark.png’ else ‘light.png’
set_globals(id[=expression] [, id[=expression]]*)
class calibre.utils.formatter_functions.BuiltinSetGlobals
set_globals(id[=expression] [, id[=expression]]*) Sets “global variables” that can be passed into the formatter.
The globals are given the name of the id passed in. The value of the id is used unless an expression is provided.
API of the Metadata objects
The python implementation of the template functions is passed in a Metadata object. Knowing it’s API is useful if you
want to dene your own template functions.
class calibre.ebooks.metadata.book.base.Metadata(title, authors=('Unknown',), other=None,
template_cache=None, formatter=None)
A class representing all the metadata for a book. The various standard metadata elds 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() (page 211) method to test if a eld is null.
This object also has functions to format elds into strings.
The list of standard metadata elds grows with time is in STANDARD_METADATA_FIELDS (page 212).
Please keep the method based API of this class to a minimum. Every method becomes a reserved eld name.
is_null(eld)
Return True if the value of eld 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 elds since this will return True for zero as well as None.
Also returns True if the eld does not exist.
deepcopy(class_generator=<function Metadata.<lambda>>)
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()
Return a copy of the identiers 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(identiers)
Set all identiers. Note that if you previously set ISBN, calling this method will delete it.
10.3. The calibre template language 211
calibre User Manual, Release 7.19.0
set_identifier(typ, val)
If val is empty, deletes identier of type typ
standard_field_keys()
return a list of all possible keys, even if this book doesn’t have them
custom_field_keys()
return a list of the custom elds in this book
all_field_keys()
All eld keys known by this instance, even if their value is None
metadata_for_field(key)
return metadata describing a standard or custom eld.
all_non_none_fields()
Return a dictionary containing all non-None metadata elds, including the custom ones.
get_standard_metadata(eld, make_copy)
return eld metadata from the eld if it is there. Otherwise return None. eld 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)
return a dict containing all the standard eld metadata associated with the book.
get_all_user_metadata(make_copy)
return a dict containing all the custom eld metadata associated with the book.
get_user_metadata(eld, make_copy)
return eld metadata from the object if it is there. Otherwise return None. eld 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)
store custom eld metadata into the object. Field is the key name not the label
set_user_metadata(eld, metadata)
store custom eld metadata for one column into the object. Field is the key name not the label
remove_stale_user_metadata(other_mi)
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)
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-eorts basis. Some assignments can make no sense.
smart_update(other, replace_metadata=False)
Merge the information in other into self. In case of conicts, the information in other takes precedence, unless
the information in other is NULL.
format_field(key, series_with_index=True)
Returns the tuple (display_name, formatted_value)
to_html()
A HTML representation of this object.
212 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
calibre.ebooks.metadata.book.base.STANDARD_METADATA_FIELDS
The set of standard metadata elds.
'''
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',
))
(continues on next page)
10.3. The calibre template language 213
calibre User Manual, Release 7.19.0
(continued from previous page)
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(
(continues on next page)
214 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
(continued from previous page)
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
10.4 All about using regular expressions in calibre
Regular expressions are features used in many places in calibre to perform sophisticated manipulation of e-book content
and metadata. This tutorial is a gentle introduction to getting you started with using regular expressions in calibre.
Contents
First, a word of warning and a word of courage (page 216)
Where in calibre can you use regular expressions? (page 216)
What on earth is a regular expression? (page 216)
Care to explain? (page 216)
That doesn’t sound too bad. What’s next? (page 217)
Hey, neat! This is starting to make sense! (page 217)
Well, these special characters are very neat and all, but what if I wanted to match a dot or a question mark?
(page 218)
So, what are the most useful sets? (page 218)
But if I had a few varying strings I wanted to match, things get complicated? (page 219)
You missed… (page 219)
In the beginning, you said there was a way to make a regular expression case insensitive? (page 219)
I think I’m beginning to understand these regular expressions now… how do I use them in calibre? (page 219)
Conversions (page 219)
Adding books (page 220)
Bulk editing metadata (page 220)
Quick reference (page 221)
Credits (page 226)
10.4. All about using regular expressions in calibre 215
calibre User Manual, Release 7.19.0
10.4.1 First, a word of warning and a word of courage
This is, inevitably, going to be somewhat technical- after all, regular expressions are a technical tool for doing technical
stu. I’m going to have to use some jargon and concepts that may seem complicated or convoluted. I’m going to try
to explain those concepts as clearly as I can, but really can’t do without using them at all. That being said, don’t be
discouraged by any jargon, as I’ve tried to explain everything new. And while regular expressions themselves may seem
like an arcane, black magic (or, to be more prosaic, a random string of mumbo-jumbo letters and signs), I promise that
they are not all that complicated. Even those who understand regular expressions really well have trouble reading the more
complex ones, but writing them isn’t as dicult- you construct the expression step by step. So, take a step and follow me
into the rabbit hole.
10.4.2 Where in calibre can you use regular expressions?
There are a few places calibre uses regular expressions. There’s the Search & replace in conversion options, metadata
detection from lenames in the import settings and Search & replace when editing the metadata of books in bulk. The cal-
ibre book editor can also use regular expressions in its Search and replace feature. Finally, you can use regular expressions
when searching the calibre book list and when searching inside the calibre E-book viewer.
10.4.3 What on earth is a regular expression?
A regular expression is a way to describe sets of strings. A single regular expression can match a number of dierent
strings. This is what makes regular expression so powerful they are a concise way of describing a potentially large
number of variations.
® Note
I’m using string here in the sense it is used in programming languages: a string of one or more characters, characters
including actual characters, numbers, punctuation and so-called whitespace (linebreaks, tabulators etc.). Please note
that generally, uppercase and lowercase characters are not considered the same, thus “a” being a dierent character
from “A” and so forth. In calibre, regular expressions are case insensitive in the Search bar, but not in the conversion
options. There’s a way to make every regular expression case insensitive, but we’ll discuss that later. It gets complicated
because regular expressions allow for variations in the strings it matches, so one expression can match multiple strings,
which is why people bother using them at all. More on that in a bit.
10.4.4 Care to explain?
Well, that’s why we’re here. First, this is the most important concept in regular expressions: A string by itself is a regular
expression that matches itself. That is to say, if I wanted to match the string "Hello, World!" using a regular
expression, the regular expression to use would be Hello, World!. And yes, it really is that simple. You’ll notice,
though, that this only matches the exact string "Hello, World!", not e.g. "Hello, wOrld!" or "hello,
world!" or any other such variation.
216 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.4.5 That doesn’t sound too bad. What’s next?
Next is the beginning of the really good stu. Remember where I said that regular expressions can match multiple strings?
This is where it gets a little more complicated. Say, as a somewhat more practical exercise, the e-book you wanted to
convert had a nasty footer counting the pages, like “Page 5 of 423”. Obviously the page number would rise from 1 to
423, thus you’d have to match 423 dierent strings, right? Wrong, actually: regular expressions allow you to dene sets of
characters that are matched: To dene a set, you put all the characters you want to be in the set into square brackets. So, for
example, the set [abc] would match either the character “a”, “b” or “c”. Sets will always only match one of the characters
in the set. They “understand” character ranges, that is, if you wanted to match all the lower case characters, you’d use the
set [a-z] for lower- and uppercase characters you’d use [a-zA-Z] and so on. Got the idea? So, obviously, using the
expression
Page [0-9] of 423
you’d be able to match the rst 9 pages, thus reducing the expressions needed to
three: The second expression Page [0-9][0-9] of 423 would match all two-digit page numbers, and I’m sure
you can guess what the third expression would look like. Yes, go ahead. Write it down.
10.4.6 Hey, neat! This is starting to make sense!
I was hoping you’d say that. But brace yourself, now it gets even better! We just saw that using sets, we could match one
of several characters at once. But you can even repeat a character or set, reducing the number of expressions needed to
handle the above page number example to one. Yes, ONE! Excited? You should be! It works like this: Some so-called
special characters, “+”, “?” and “*”, repeat the single element preceding them. (Element means either a single character, a
character set, an escape sequence or a group (we’ll learn about those last two later)- in short, any single entity in a regular
expression). These characters are called wildcards or quantiers. To be more precise, “?” matches 0 or 1 of the preceding
element, “*” matches 0 or more of the preceding element and “+” matches 1 or more of the preceding element. A few
examples: The expression a? would match either “” (which is the empty string, not strictly useful in this case) or “a”,
the expression a* would match “”, “a”, “aa” or any number of a’s in a row, and, nally, the expression a+ would match
“a”, “aa” or any number of a’s in a row (Note: it wouldn’t match the empty string!). Same deal for sets: The expression
[0-9]+ would match every integer number there is! I know what you’re thinking, and you’re right: If you use that in the
above case of matching page numbers, wouldn’t that be the single one expression to match all the page numbers? Yes,
the expression Page [0-9]+ of 423 would match every page number in that book!
® Note
A note on these quantiers: They generally try to match as much text as possible, so be careful when using them. This
is called “greedy behaviour”- I’m sure you get why. It gets problematic when you, say, try to match a tag. Consider,
for example, the string "<p class="calibre2">Title here</p>" and let’s say you’d want to match the
opening tag (the part between the rst pair of angle brackets, a little more on tags later). You’d think that the expression
<p.*> would match that tag, but actually, it matches the whole string! (The character “.” is another special character.
It matches anything except linebreaks, so, basically, the expression .* would match any single line you can think of).
Instead, try using <p.*?> which makes the quantier "*" non-greedy. That expression would only match the rst
opening tag, as intended. There’s actually another way to accomplish this: The expression <p[^>]*> will match
that same opening tag- you’ll see why after the next section. Just note that there quite frequently is more than one way
to write a regular expression.
10.4. All about using regular expressions in calibre 217
calibre User Manual, Release 7.19.0
10.4.7 Well, these special characters are very neat and all, but what if I wanted to
match a dot or a question mark?
You can of course do that: Just put a backslash in front of any special character and it is interpreted as the literal character,
without any special meaning. This pair of a backslash followed by a single character is called an escape sequence, and
the act of putting a backslash in front of a special character is called escaping that character. An escape sequence is
interpreted as a single element. There are of course escape sequences that do more than just escaping special characters,
for example "\t" means a tabulator. We’ll get to some of the escape sequences later. Oh, and by the way, concerning
those special characters: Consider any character we discuss in this introduction as having some function to be special and
thus needing to be escaped if you want the literal character.
10.4.8 So, what are the most useful sets?
Knew you’d ask. Some useful sets are [0-9] matching a single number, [a-z] matching a single lowercase letter,
[A-Z] matching a single uppercase letter, [a-zA-Z] matching a single letter and [a-zA-Z0-9] matching a single
letter or number. You can also use an escape sequence as shorthand:
\d
is equivalent to [0-9]
\w
is equivalent to [a-zA-Z0-9_]
\s
is equivalent to any whitespace
® Note
“Whitespace” is a term for anything that won’t be printed. These characters include space, tabulator, line feed, form
feed, carriage return, non-breaking spaces, etc.
® Note
The upper and lower case sets may match both upper and lowercase if the setting to make searches case insensitive is
enabled. Such settings are found, for instance in Preferences->Searching in calibre itself and on the Search panel in
the calibre E-book viewer as well as the calibre Edit book tool.
As a last note on sets, you can also dene a set as any character but those in the set. You do that by including the
character "^" as the very rst character in the set. Thus, [^a] would match any character excluding “a”. That’s called
complementing the set. Those escape sequence shorthands we saw earlier can also be complemented: "\D" means any
non-number character, thus being equivalent to [^0-9]. The other shorthands can be complemented by, you guessed
it, using the respective uppercase letter instead of the lowercase one. So, going back to the example <p[^>]*> from the
previous section, now you can see that the character set it’s using tries to match any character except for a closing angle
bracket.
218 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.4.9 But if I had a few varying strings I wanted to match, things get complicated?
Fear not, life still is good and easy. Consider this example: The book you’re converting has “Title” written on every odd
page and “Author” written on every even page. Looks great in print, right? But in e-books, it’s annoying. You can group
whole expressions in normal parentheses, and the character
"|"
will let you match
either
the expression to its right
or
the
one to its left. Combine those and you’re done. Too fast for you? Okay, rst o, we group the expressions for odd and
even pages, thus getting (Title)(Author) as our two needed expressions. Now we make things simpler by using
the vertical bar ("|" is called the vertical bar character): If you use the expression (Title|Author) you’ll either get
a match for “Title” (on the odd pages) or you’d match “Author” (on the even pages). Well, wasn’t that easy?
You can, of course, use the vertical bar without using grouping parentheses, as well. Remember when I said that quantiers
repeat the element preceding them? Well, the vertical bar works a little dierently: The expression “Title|Author” will also
match either the string “Title” or the string “Author”, just as the above example using grouping. The vertical bar selects
between the entire expression preceding and following it. So, if you wanted to match the strings “Calibre” and “calibre”
and wanted to select only between the upper- and lowercase “c”, you’d have to use the expression (c|C)alibre, where
the grouping ensures that only the “c” will be selected. If you were to use c|Calibre, you’d get a match on the string
“c” or on the string “Calibre”, which isn’t what we wanted. In short: If in doubt, use grouping together with the vertical
bar.
10.4.10 You missed…
wait just a minute, there’s one last, really neat thing you can do with groups. If you have a group that you previously
matched, you can use references to that group later in the expression: Groups are numbered starting with 1, and you
reference them by escaping the number of the group you want to reference, thus, the fth group would be referenced as
\5. So, if you searched for ([^ ]+) \1 in the string “Test Test”, you’d match the whole string!
10.4.11 In the beginning, you said there was a way to make a regular expression
case insensitive?
Yes, I did, thanks for paying attention and reminding me. You can tell calibre how you want certain things handled by
using something called ags. You include ags in your expression by using the special construct (?flags go here)
where, obviously, you’d replace “ags go here” with the specic ags you want. For ignoring case, the ag is i, thus you
include (?i) in your expression. Thus, (?i)test would match “Test”, “tEst”, “TEst” and any case variation you could
think of.
Another useful ag lets the dot match any character at all, including the newline, the ag s. If you want to use multiple
ags in an expression, just put them in the same statement: (?is) would ignore case and make the dot match all. It
doesn’t matter which ag you state rst, (?si) would be equivalent to the above.
10.4.12 I think I’m beginning to understand these regular expressions now… how
do I use them in calibre?
Conversions
Let’s begin with the conversion settings, which is really neat. In the Search & replace part, you can input a regexp (short
for regular expression) that describes the string that will be replaced during the conversion. The neat part is the wizard.
Click on the wizard sta and you get a preview of what calibre “sees” during the conversion process. Scroll down to the
string you want to remove, select and copy it, paste it into the regexp eld on top of the window. If there are variable
parts, like page numbers or so, use sets and quantiers to cover those, and while you’re at it, remember to escape special
characters, if there are some. Hit the button labeled Test and calibre highlights the parts it would replace were you to use
the regexp. Once you’re satised, hit OK and convert. Be careful if your conversion source has tags like this example:
10.4. All about using regular expressions in calibre 219
calibre User Manual, Release 7.19.0
Maybe, but the cops feel like you do, Anita. What's one more dead vampire?
New laws don't change that. </p>
<p class="calibre4"> <b class="calibre2">Generated by ABC Amber LIT Conv
<a href="http://www.processtext.com/abclit.html" class="calibre3">erter,
http://www.processtext.com/abclit.html</a></b></p>
<p class="calibre4"> It had only been two years since Addison v. Clark.
The court case gave us a revised version of what life was
(shamelessly ripped out of this thread
94
). You’d have to remove some of the tags as well. In this example, I’d recommend
beginning with the tag <b class="calibre2">, now you have to end with the corresponding closing tag (opening
tags are <tag>, closing tags are </tag>), which is simply the next </b> in this case. (Refer to a good HTML manual or
ask in the forum if you are unclear on this point). The opening tag can be described using <b.*?>, the closing tag using
</b>, thus we could remove everything between those tags using <b.*?>.*?</b>. But using this expression would be
a bad idea, because it removes everything enclosed by <b>- tags (which, by the way, render the enclosed text in bold print),
and it’s a fair bet that we’ll remove portions of the book in this way. Instead, include the beginning of the enclosed string
as well, making the regular expression <b.*?>\s*Generated\s+by\s+ABC\s+Amber\s+LIT.*?</b> The
\s with quantiers are included here instead of explicitly using the spaces as seen in the string to catch any variations of
the string that might occur. Remember to check what calibre will remove to make sure you don’t remove any portions
you want to keep if you test a new expression. If you only check one occurrence, you might miss a mismatch somewhere
else in the text. Also note that should you accidentally remove more or fewer tags than you actually wanted to, calibre
tries to repair the damaged code after doing the removal.
Adding books
Another thing you can use regular expressions for is to extract metadata from lenames. You can nd this feature in
the “Adding books” part of the settings. There’s a special feature here: You can use eld names for metadata elds, for
example (?P<title>) would indicate that calibre uses this part of the string as book title. The allowed eld names are
listed in the windows, together with another nice test eld. An example: Say you want to import a whole bunch of les
named like Classical Texts: The Divine Comedy by Dante Alighieri.mobi. (Obviously, this is
already in your library, since we all love classical italian poetry) or Science Fiction epics: The Foundation
Trilogy by Isaac Asimov.epub. This is obviously a naming scheme that calibre won’t extract any meaningful
data out of - its standard expression for extracting metadata is (?P<title>.+) - (?P<author>[^_]+). A
regular expression that works here would be [a-zA-Z]+: (?P<title>.+) by (?P<author>.+). Please
note that, inside the group for the metadata eld, you need to use expressions to describe what the eld actually matches.
And also note that, when using the test eld calibre provides, you need to add the le extension to your testing lename,
otherwise you won’t get any matches at all, despite using a working expression.
Bulk editing metadata
The last part is regular expression Search and replace in metadata elds. You can access this by selecting multiple books
in the library and using bulk metadata edit. Be very careful when using this last feature, as it can do Very Bad Things
to your library! Doublecheck that your expressions do what you want them to using the test elds, and only mark the
books you really want to change! In the regular expression search mode, you can search in one eld, replace the text
with something and even write the result into another eld. A practical example: Say your library contained the books of
Frank Herbert’s Dune series, named after the fashion Dune 1 - Dune, Dune 2 - Dune Messiah and so on.
Now you want to get Dune into the series eld. You can do that by searching for (.*?) \d+ - .* in the title eld
and replacing it with \1 in the series eld. See what I did there? That’s a reference to the rst group you’re replacing the
series eld with. Now that you have the series all set, you only need to do another search for .*? - in the title eld and
replace it with "" (an empty string), again in the title eld, and your metadata is all neat and tidy. Isn’t that great? By
the way, instead of replacing the entire eld, you can also append or prepend to the eld, so, if you wanted the book title
94
https://www.mobileread.com/forums/showthread.php?t=75594"
220 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
to be prepended with series info, you could do that as well. As you by now have undoubtedly noticed, there’s a checkbox
labeled Case sensitive, so you won’t have to use ags to select behaviour here.
Well, that just about concludes the very short introduction to regular expressions. Hopefully I’ll have shown you enough
to at least get you started and to enable you to continue learning by yourself- a good starting point would be the Python
documentation for regexps
95
.
One last word of warning, though: Regexps are powerful, but also really easy to get wrong. calibre provides really great
testing possibilities to see if your expressions behave as you expect them to. Use them. Try not to shoot yourself in the
foot. (God, I love that expression…). But should you, despite the warning, injure your foot (or any other body parts), try
to learn from it.
10.4.13 Quick reference
Quick reference for regexp syntax
This checklist summarizes the most commonly used/hard to remember parts of the regexp engine available in most parts
of calibre.
Contents
Character classes (page 222)
Shorthand character classes (page 222)
The quantiers (page 222)
Greed (page 223)
Alternation (page 223)
Exclusion (page 223)
Anchors (page 223)
Groups (page 224)
Lookarounds (page 224)
Recursion (page 225)
Special characters (page 225)
Meta-characters (page 225)
Modes (page 226)
95
https://docs.python.org/library/re.html
10.4. All about using regular expressions in calibre 221
calibre User Manual, Release 7.19.0
Character classes
Character classes are useful to represent dierent groups of characters, succinctly.
Examples:
Representa-
tion
Class
[a-z] Lowercase letters. Does not include characters with accent mark and ligatures
[a-z0-9] Lowercase letters from a to z or numbers from 0 to 9
[A-Za-z-] Uppercase or lowercase letters, or a dash. To include the dash in a class, you must put it at the
beginning or at the end so as not to confuse it with the hyphen that species a range of characters
[^0-9] Any character except a digit. The caret (^) placed at the beginning of the class excludes the characters
of the class (complemented class)
[[a-z]--[aeiouy]]The lowercase consonants. A class can be included in a class. The characters -- exclude what follows
them
[\w--[\
d_]]
All letters (including foreign accented characters). Abbreviated classes can be used inside a class
Example:
<[^<>]+> to select an HTML tag
Shorthand character classes
Representa-
tion
Class
\d A digit (same as [0-9])
\D Any non-numeric character (same as [^0-9])
\w An alphanumeric character ([a-zA-Z0-9]) including characters with accent mark and ligatures
\W Any “non-word” character
\s Space, non-breaking space, tab, return line
\S Any “non-whitespace” character
. Any character except newline. Use the “dot all” checkbox or the (?s) regexp modier to include
the newline character.
The quantiers
Quantier Number of occurrences of the expression preceding the quantier
? 0 or 1 occurrence of the expression. Same as {0,1}
+ 1 or more occurrences of the expression. Same as {1,}
* 0, 1 or more occurrences of the expression. Same as {0,}
{n} Exactly n occurrences of the expression
{min,max} Number of occurrences between the minimum and maximum values included
{min,} Number of occurrences between the minimum value included and the innite
{,max} Number of occurrences between 0 and the maximum value included
222 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
Greed
By default, with quantiers, the regular expression engine is greedy: it extends the selection as much as possible. This
often causes surprises, at rst. ? follows a quantier to make it lazy. Avoid putting two in the same expression, the result
can be unpredictable.
Beware of nesting quantiers, for example, the pattern (a*)*, as it exponentially increases processing time.
Alternation
The | character in a regular expression is a logical OR. It means that either the preceding or the following expression can
match.
Exclusion
Method 1
pattern_to_exclude(*SKIP)(*FAIL)|pattern_to_select
Example:
"Blabla"(*SKIP)(*FAIL)|Blabla
selects Blabla, in the strings Blabla or “Blabla or Blabla”, but not in “Blabla”.
Method 2
pattern_to_exclude\K|(pattern_to_select)
"Blabla"\K|(Blabla)
selects Blabla, in the strings Blabla or “Blabla or Blabla”, but not in “Blabla”.
Anchors
An anchor is a way to match a logical location in a string, rather than a character. The most useful anchors for text
processing are:
\b
Designates a word boundary, i.e. a transition from space to non-space character. For example, you can
use \bsurd to match the surd but not absurd.
^
Matches the start of a line (in multi-line mode, which is the default)
$
Matches the end of a line (in multi-line mode, which is the default)
\K
Resets the start position of the selection to its position in the pattern. Some regexp engines (but not
calibre) do not allow lookbehind of variable length, especially with quantiers. When you can use \K
with these engines, it also allows you to get rid of this limit by writing the equivalent of a positive
lookbehind of variable length.
10.4. All about using regular expressions in calibre 223
calibre User Manual, Release 7.19.0
Groups
(expression)
Capturing group, which stores the selection and can be recalled later in the search or replace patterns
with \n, where n is the sequence number of the capturing group (starting at 1 in reading order)
(?:expression)
Group that does not capture the selection
(?>expression)
Atomic Group: As soon as the expression is satised, the regexp engine passes, and if the rest of the
pattern fails, it will not backtrack to try other combinations with the expression. Atomic groups do not
capture.
(?|expression)
Branch reset group: the branches of the alternations included in the expression share the same group
numbers
(?<name>expression)
Group named “name”. The selection can be recalled later in the search pattern by (?P=name) and
in the replace by \g<name>. Two dierent groups can use the same name.
Lookarounds
Lookaround Meaning
?= Positive lookahead (to be placed after the selection)
?! Negative lookahead (to be placed after the selection)
?<= Positive lookbehind (to be placed before the selection)
?<! Negative lookbehind (to be placed before the selection)
Lookaheads and lookbehinds do not consume characters, they are zero length and do not capture. They are atomic groups:
as soon as the assertion is satised, the regexp engine passes, and if the rest of the pattern fails, it will not backtrack inside
the lookaround to try other combinations.
When looking for multiple matches in a string, at the starting position of each match attempt, a lookbehind can inspect
the characters before the current position. Therefore, on the string 123, the pattern (?<=\d)\d (a digit preceded by
a digit) should, in theory, select 2 and 3. On the other hand, \d\K\d can only select 2, because the starting position
after the rst selection is immediately before 3, and there are not enough digits for a second match. Similarly, \d(\d)
only captures 2. In calibre’s regexp engine practice, the positive lookbehind behaves in the same way, and selects only 2,
contrary to theory.
Groups can be placed inside lookarounds, but capture is rarely useful. Nevertheless, if it is useful, it will be necessary
to be very careful in the use of a quantier in a lookbehind: the greed associated with the absence of backtracking can
give a surprising capture. For this reason, use \K rather than a positive lookbehind when you have a quantier (or worse,
several) in a capturing group of the positive lookbehind.
Example of negative lookahead:
(?![^<>{}]*[>}])
Placed at the end of the pattern prevents to select within a tag or a style embedded in the le.
Whenever possible, it is always better to “anchor” the lookarounds, to reduce the number of steps necessary to obtain the
result.
224 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
Recursion
Representation Meaning
(?R) Recursion of the entire pattern
(?1) Recursion of the only pattern of the numbered capturing group, here group 1
Recursion is calling oneself. This is useful for balanced queries, such as quoted strings, which can contain embedded
quoted strings. Thus, if during the processing of a string between double quotation marks, we encounter the beginning
of a new string between double quotation marks, well we know how to do, and we call ourselves. Then we have a pattern
like:
start-pattern(?>atomic sub-pattern|(?R))*end-pattern
To select a string between double quotation marks without stopping on an embedded string:
“((?>[^“”]+|(?R))*[^“”]+)”
This template can also be used to modify pairs of tags that can be embedded, such as <div> tags.
Special characters
Representation Character
\t tabulation
\n line break
\x20 (breakable) space
\xa0 no-break space
Meta-characters
Meta-characters are those that have a special meaning for the regexp engine. Of these, twelve must be preceded by an
escape character, the backslash (\), to lose their special meaning and become a regular character again:
^ . [ ] $ ( ) * + ? | \
Seven other meta-characters do not need to be preceded by a backslash (but can be without any other consequence):
{ } ! < > = :
Special characters lose their status if they are used inside a class (between brackets []). The closing bracket and the dash
have a special status in a class. Outside the class, the dash is a simple literal, the closing bracket remains a meta-character.
The slash (/) and the number sign (or hash character) (#) are not meta-characters, they don’t need to be escaped.
In some tools, like regex101.com with the Python engine, double quotes have the special status of separator, and must be
escaped, or the options changed. This is not the case in the editor of calibre.
10.4. All about using regular expressions in calibre 225
calibre User Manual, Release 7.19.0
Modes
(?s)
Causes the dot (.) to match newline characters as well
(?m)
Makes the ^ and $ anchors match the start and end of lines instead of the start and end of the entire
string.
10.4.14 Credits
Thanks for helping with tips, corrections and such:
ldolse
kovidgoyal
chaley
dwanthny
kacir
Starson17
Orpheu
For more about regexps see The Python User Manual
96
. The actual regular expression library used by calibre is: regex
97
which supports several useful enhancements over the Python standard library one.
10.5 Writing your own plugins to extend calibre’s functionality
calibre has a very modular design. Almost all functionality in calibre comes in the form of plugins. Plugins are used
for conversion, for downloading news (though these are called recipes), for various components of the user interface, to
connect to dierent devices, to process les when adding them to calibre and so on. You can get a complete list of all the
built-in plugins in calibre by going to Preferences → Advanced → Plugins.
Here, we will teach you how to create your own plugins to add new features to calibre.
Contents
Anatomy of a calibre plugin (page 227)
A User Interface plugin (page 228)
__init__.py (page 229)
ui.py (page 230)
main.py (page 231)
Getting resources from the plugin ZIP le (page 234)
Enabling user conguration of your plugin (page 234)
96
https://docs.python.org/library/re.html
97
https://bitbucket.org/mrabarnett/mrab-regex/src/hg/
226 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
Edit book plugins (page 236)
main.py (page 237)
Adding translations to your plugin (page 239)
The plugin API (page 240)
Debugging plugins (page 240)
More plugin examples (page 241)
Sharing your plugins with others (page 241)
® Note
This only applies to calibre releases >= 0.8.60
10.5.1 Anatomy of a calibre plugin
A calibre plugin is very simple, it’s just a ZIP le that contains some Python code and any other resources like image les
needed by the plugin. Without further ado, let’s see a basic example.
Suppose you have an installation of calibre that you are using to self publish various e-documents in EPUB and MOBI
formats. You would like all les generated by calibre to have their publisher set as “Hello world”, here’s how to do it.
Create a le named __init__.py (this is a special name and must always be used for the main le of your plugin) and
enter the following Python code into it:
from calibre.customize import FileTypePlugin
class HelloWorld(FileTypePlugin):
name = 'Hello World Plugin' # Name of the plugin
description = 'Set the publisher to Hello World for all new conversions'
supported_platforms = ['windows', 'osx', 'linux'] # Platforms this plugin will
,run on
author = 'Acme Inc.' # The author of this plugin
version = (1, 0, 0) # The version number of this plugin
file_types = {'epub', 'mobi'} # The file types that this plugin will be
,applied to
on_postprocess = True # Run this plugin after conversion is complete
minimum_calibre_version = (0, 7, 53)
def run(self, path_to_ebook):
from calibre.ebooks.metadata.meta import get_metadata, set_metadata
with open(path_to_ebook, 'r+b') as file:
ext = os.path.splitext(path_to_ebook)[-1][1:].lower()
mi = get_metadata(file, ext)
mi.publisher = 'Hello World'
set_metadata(file, mi, ext)
return path_to_ebook
That’s all. To add this code to calibre as a plugin, simply run the following in the folder in which you created __init__.
py:
10.5. Writing your own plugins to extend calibre’s functionality 227
calibre User Manual, Release 7.19.0
calibre-customize -b .
® Note
On macOS, the command line tools are inside the calibre bundle, for example, if you installed calibre in /
Applications the command line tools are in /Applications/calibre.app/Contents/MacOS/.
You can download the Hello World plugin from helloworld_plugin.zip
98
.
Every time you use calibre to convert a book, the plugin’s run() method will be called and the converted book will have
its publisher set to “Hello World”. This is a trivial plugin, lets move on to a more complex example that actually adds a
component to the user interface.
10.5.2 A User Interface plugin
This plugin will be spread over a few les (to keep the code clean). It will show you how to get resources (images or data
les) from the plugin ZIP le, allow users to congure your plugin, how to create elements in the calibre user interface
and how to access and query the books database in calibre.
You can download this plugin from interface_demo_plugin.zip
99
The rst thing to note is that this ZIP le has a lot more les in it, explained below, pay particular attention to
plugin-import-name-interface_demo.txt.
plugin-import-name-interface_demo.txt
An empty text le used to enable the multi-le plugin magic. This le must be present in all plu-
gins that use more than one .py le. It should be empty and its lename must be of the form:
plugin-import-name-**some_name**.txt. The presence of this le allows you to import
code from the .py les present inside the ZIP le, using a statement like:
from calibre_plugins.some_name.some_module import some_object
The prex calibre_plugins must always be present. some_name comes from the lename of
the empty text le.
some_module
refers to
some_module.py
le inside the ZIP le. Note that
this importing is just as powerful as regular Python imports. You can create packages and subpackages
of .py modules inside the ZIP le, just like you would normally (by dening __init__.py in each sub-
folder), and everything should “just work”.
The name you use for some_name enters a global namespace shared by all plugins, so make it as
unique as possible. But remember that it must be a valid Python identier (only alphabets, numbers
and the underscore).
__init__.py
As before, the le that denes the plugin class
main.py
This le contains the actual code that does something useful
ui.py
This le denes the interface part of the plugin
images/icon.png
The icon for this plugin
98
https://calibre-ebook.com/downloads/helloworld_plugin.zip
99
https://calibre-ebook.com/downloads/interface_demo_plugin.zip
228 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
about.txt
A text le with information about the plugin
translations
A folder containing .mo les with the translations of the user interface of your plugin into dierent
languages. See below for details.
Now let’s look at the code.
__init__.py
First, the obligatory __init__.py to dene the plugin metadata:
from calibre.customize import InterfaceActionBase
class InterfacePluginDemo(InterfaceActionBase):
'''
This class is a simple wrapper that provides information about the actual
plugin class. The actual interface plugin class is called InterfacePlugin
and is defined in the ui.py file, as specified in the actual_plugin field
below.
The reason for having two classes is that it allows the command line
calibre utilities to run without needing to load the GUI libraries.
'''
name = 'Interface Plugin Demo'
description = 'An advanced plugin demo'
supported_platforms = ['windows', 'osx', 'linux']
author = 'Kovid Goyal'
version = (1, 0, 0)
minimum_calibre_version = (0, 7, 53)
#: This field defines the GUI plugin class that contains all the code
#: that actually does something. Its format is module_path:class_name
#: The specified class must be defined in the specified module.
actual_plugin = 'calibre_plugins.interface_demo.ui:InterfacePlugin'
def is_customizable(self):
'''
This method must return True to enable customization via
Preferences->Plugins
'''
return True
def config_widget(self):
'''
Implement this method and :meth:`save_settings` in your plugin to
use a custom configuration dialog.
This method, if implemented, must return a QWidget. The widget can have
an optional method validate() that takes no arguments and is called
immediately after the user clicks OK. Changes are applied if and only
if the method returns True.
If for some reason you cannot perform the configuration at this time,
return a tuple of two strings (message, details), these will be
(continues on next page)
10.5. Writing your own plugins to extend calibre’s functionality 229
calibre User Manual, Release 7.19.0
(continued from previous page)
displayed as a warning dialog to the user and the process will be
aborted.
The base class implementation of this method raises NotImplementedError
so by default no user configuration is possible.
'''
# It is important to put this import statement here rather than at the
# top of the module as importing the config class will also cause the
# GUI libraries to be loaded, which we do not want when using calibre
# from the command line
from calibre_plugins.interface_demo.config import ConfigWidget
return ConfigWidget()
def save_settings(self, config_widget):
'''
Save the settings specified by the user with config_widget.
:param config_widget: The widget returned by :meth:`config_widget`.
'''
config_widget.save_settings()
# Apply the changes
ac = self.actual_plugin_
if ac is not None:
ac.apply_settings()
The only noteworthy feature is the eld actual_plugin. Since calibre has both command line and GUI interfaces,
GUI plugins like this one should not load any GUI libraries in __init__.py. The actual_plugin eld does this for you, by
telling calibre that the actual plugin is to be found in another le inside your ZIP archive, which will only be loaded in a
GUI context.
Remember that for this to work, you must have a plugin-import-name-some_name.txt le in your plugin ZIP le, as
discussed above.
Also there are a couple of methods for enabling user conguration of the plugin. These are discussed below.
ui.py
Now let’s look at ui.py which denes the actual GUI plugin. The source code is heavily commented and should be self
explanatory:
from calibre.gui2.actions import InterfaceAction
from calibre_plugins.interface_demo.main import DemoDialog
class InterfacePlugin(InterfaceAction):
name = 'Interface Plugin Demo'
# Declare the main action associated with this plugin
# The keyboard shortcut can be None if you dont want to use a keyboard
# shortcut. Remember that currently calibre has no central management for
# keyboard shortcuts, so try to use an unusual/unused shortcut.
action_spec = ('Interface Plugin Demo', None,
(continues on next page)
230 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
(continued from previous page)
'Run the Interface Plugin Demo', 'Ctrl+Shift+F1')
def genesis(self):
# This method is called once per plugin, do initial setup here
# Set the icon for this interface action
# The get_icons function is a builtin function defined for all your
# plugin code. It loads icons from the plugin zip file. It returns
# QIcon objects, if you want the actual data, use the analogous
# get_resources builtin function.
#
# Note that if you are loading more than one icon, for performance, you
# should pass a list of names to get_icons. In this case, get_icons
# will return a dictionary mapping names to QIcons. Names that
# are not found in the zip file will result in null QIcons.
icon = get_icons('images/icon.png', 'Interface Demo Plugin')
# The qaction is automatically created from the action_spec defined
# above
self.qaction.setIcon(icon)
self.qaction.triggered.connect(self.show_dialog)
def show_dialog(self):
# The base plugin object defined in __init__.py
base_plugin_object = self.interface_action_base_plugin
# Show the config dialog
# The config dialog can also be shown from within
# Preferences->Plugins, which is why the do_user_config
# method is defined on the base plugin class
do_user_config = base_plugin_object.do_user_config
# self.gui is the main calibre GUI. It acts as the gateway to access
# all the elements of the calibre user interface, it should also be the
# parent of the dialog
d = DemoDialog(self.gui, self.qaction.icon(), do_user_config)
d.show()
def apply_settings(self):
from calibre_plugins.interface_demo.config import prefs
# In an actual non trivial plugin, you would probably need to
# do something based on the settings in prefs
prefs
main.py
The actual logic to implement the Interface Plugin Demo dialog.
from qt.core import QDialog, QLabel, QMessageBox, QPushButton, QVBoxLayout
class DemoDialog(QDialog):
def __init__(self, gui, icon, do_user_config):
QDialog.__init__(self, gui)
self.gui = gui
(continues on next page)
10.5. Writing your own plugins to extend calibre’s functionality 231
calibre User Manual, Release 7.19.0
(continued from previous page)
self.do_user_config = do_user_config
# The current database shown in the GUI
# db is an instance of the class LibraryDatabase from db/legacy.py
# This class has many, many methods that allow you to do a lot of
# things. For most purposes you should use db.new_api, which has
# a much nicer interface from db/cache.py
self.db = gui.current_db
self.l = QVBoxLayout()
self.setLayout(self.l)
self.label = QLabel(prefs['hello_world_msg'])
self.l.addWidget(self.label)
self.setWindowTitle('Interface Plugin Demo')
self.setWindowIcon(icon)
self.about_button = QPushButton('About', self)
self.about_button.clicked.connect(self.about)
self.l.addWidget(self.about_button)
self.marked_button = QPushButton(
'Show books with only one format in the calibre GUI', self)
self.marked_button.clicked.connect(self.marked)
self.l.addWidget(self.marked_button)
self.view_button = QPushButton(
'View the most recently added book', self)
self.view_button.clicked.connect(self.view)
self.l.addWidget(self.view_button)
self.update_metadata_button = QPushButton(
'Update metadata in a book\'s files', self)
self.update_metadata_button.clicked.connect(self.update_metadata)
self.l.addWidget(self.update_metadata_button)
self.conf_button = QPushButton(
'Configure this plugin', self)
self.conf_button.clicked.connect(self.config)
self.l.addWidget(self.conf_button)
self.resize(self.sizeHint())
def about(self):
# Get the about text from a file inside the plugin zip file
# The get_resources function is a builtin function defined for all your
# plugin code. It loads files from the plugin zip file. It returns
# the bytes from the specified file.
#
# Note that if you are loading more than one file, for performance, you
# should pass a list of names to get_resources. In this case,
# get_resources will return a dictionary mapping names to bytes. Names that
# are not found in the zip file will not be in the returned dictionary.
text = get_resources('about.txt')
QMessageBox.about(self, 'About the Interface Plugin Demo',
text.decode('utf-8'))
(continues on next page)
232 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
(continued from previous page)
def marked(self):
''' Show books with only one format '''
db = self.db.new_api
matched_ids = {book_id for book_id in db.all_book_ids() if len(db.
,formats(book_id)) == 1}
# Mark the records with the matching ids
# new_api does not know anything about marked books, so we use the full
# db object
self.db.set_marked_ids(matched_ids)
# Tell the GUI to search for all marked records
self.gui.search.setEditText('marked:true')
self.gui.search.do_search()
def view(self):
''' View the most recently added book '''
most_recent = most_recent_id = None
db = self.db.new_api
for book_id, timestamp in db.all_field_for('timestamp', db.all_book_ids()).
,items():
if most_recent is None or timestamp > most_recent:
most_recent = timestamp
most_recent_id = book_id
if most_recent_id is not None:
# Get a reference to the View plugin
view_plugin = self.gui.iactions['View']
# Ask the view plugin to launch the viewer for row_number
view_plugin._view_calibre_books([most_recent_id])
def update_metadata(self):
'''
Set the metadata in the files in the selected book's record to
match the current metadata in the database.
'''
from calibre.ebooks.metadata.meta import set_metadata
from calibre.gui2 import error_dialog, info_dialog
# Get currently selected books
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) == 0:
return error_dialog(self.gui, 'Cannot update metadata',
'No books selected', show=True)
# Map the rows to book ids
ids = list(map(self.gui.library_view.model().id, rows))
db = self.db.new_api
for book_id in ids:
# Get the current metadata for this book from the db
mi = db.get_metadata(book_id, get_cover=True, cover_as_data=True)
fmts = db.formats(book_id)
if not fmts:
continue
for fmt in fmts:
fmt = fmt.lower()
# Get a python file object for the format. This will be either
# an in memory file or a temporary on disk file
(continues on next page)
10.5. Writing your own plugins to extend calibre’s functionality 233
calibre User Manual, Release 7.19.0
(continued from previous page)
ffile = db.format(book_id, fmt, as_file=True)
ffile.seek(0)
# Set metadata in the format
set_metadata(ffile, mi, fmt)
ffile.seek(0)
# Now replace the file in the calibre library with the updated
# file. We dont use add_format_with_hooks as the hooks were
# already run when the file was first added to calibre.
db.add_format(book_id, fmt, ffile, run_hooks=False)
info_dialog(self, 'Updated files',
'Updated the metadata in the files of %d book(s)'%len(ids),
show=True)
def config(self):
self.do_user_config(parent=self)
# Apply the changes
self.label.setText(prefs['hello_world_msg'])
Getting resources from the plugin ZIP le
calibre’s plugin loading system denes a couple of built-in functions that allow you to conveniently get les from the plugin
ZIP le.
get_resources(name_or_list_of_names)
This function should be called with a list of paths to les inside the ZIP le. For example to access the
le icon.png in the folder images in the ZIP le, you would use: images/icon.png. Always
use a forward slash as the path separator, even on Windows. When you pass in a single name, the
function will return the raw bytes of that le or None if the name was not found in the ZIP le. If you
pass in more than one name then it returns a dictionary mapping the names to bytes. If a name is not
found, it will not be present in the returned dictionary.
get_icons(name_or_list_of_names, plugin_name=’’)
A wrapper for get_resources() that creates QIcon objects from the raw bytes returned by get_resources.
If a name is not found in the ZIP le the corresponding QIcon will be null. In order to support icon
theme-ing, pass in the human friendly name of your plugin as plugin_name. If the user is using an
icon theme with icons for your plugin, they will be loaded preferentially.
Enabling user conguration of your plugin
To allow users to congure your plugin, you must dene three methods in your base plugin class, is_customizable,
cong_widget and save_settings as shown below:
def is_customizable(self):
'''
This method must return True to enable customization via
Preferences->Plugins
'''
return True
def config_widget(self):
'''
Implement this method and :meth:`save_settings` in your plugin to
(continues on next page)
234 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
(continued from previous page)
use a custom configuration dialog.
This method, if implemented, must return a QWidget. The widget can have
an optional method validate() that takes no arguments and is called
immediately after the user clicks OK. Changes are applied if and only
if the method returns True.
If for some reason you cannot perform the configuration at this time,
return a tuple of two strings (message, details), these will be
displayed as a warning dialog to the user and the process will be
aborted.
The base class implementation of this method raises NotImplementedError
so by default no user configuration is possible.
'''
# It is important to put this import statement here rather than at the
# top of the module as importing the config class will also cause the
# GUI libraries to be loaded, which we do not want when using calibre
# from the command line
from calibre_plugins.interface_demo.config import ConfigWidget
return ConfigWidget()
def save_settings(self, config_widget):
'''
Save the settings specified by the user with config_widget.
:param config_widget: The widget returned by :meth:`config_widget`.
'''
config_widget.save_settings()
# Apply the changes
ac = self.actual_plugin_
if ac is not None:
ac.apply_settings()
calibre has many dierent ways to store conguration data (a legacy of its long history). The recommended way is to use
the JSONCong class, which stores your conguration information in a .json le.
The code to manage conguration data in the demo plugin is in cong.py:
from qt.core import QHBoxLayout, QLabel, QLineEdit, QWidget
# This is where all preferences for this plugin will be stored
# Remember that this name (i.e. plugins/interface_demo) is also
# in a global namespace, so make it as unique as possible.
# You should always prefix your config file name with plugins/,
# so as to ensure you dont accidentally clobber a calibre config file
prefs = JSONConfig('plugins/interface_demo')
# Set defaults
prefs.defaults['hello_world_msg'] = 'Hello, World!'
class ConfigWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
(continues on next page)
10.5. Writing your own plugins to extend calibre’s functionality 235
calibre User Manual, Release 7.19.0
(continued from previous page)
self.l = QHBoxLayout()
self.setLayout(self.l)
self.label = QLabel('Hello world &message:')
self.l.addWidget(self.label)
self.msg = QLineEdit(self)
self.msg.setText(prefs['hello_world_msg'])
self.l.addWidget(self.msg)
self.label.setBuddy(self.msg)
def save_settings(self):
prefs['hello_world_msg'] = self.msg.text()
The prefs object is now available throughout the plugin code by a simple:
from calibre_plugins.interface_demo.config import prefs
You can see the prefs object being used in main.py:
self.do_user_config(parent=self)
# Apply the changes
self.label.setText(prefs['hello_world_msg'])
10.5.3 Edit book plugins
Now let’s change gears for a bit and look at creating a plugin to add tools to the calibre book editor. The plugin is available
here: editor_demo_plugin.zip
100
.
The rst step, as for all plugins is to create the import name empty txt le, as described above (page 228). We shall name
the le plugin-import-name-editor_plugin_demo.txt.
Now we create the mandatory __init__.py le that contains metadata about the plugin its name, author, version,
etc.
from calibre.customize import EditBookToolPlugin
class DemoPlugin(EditBookToolPlugin):
name = 'Edit Book plugin demo'
version = (1, 0, 0)
author = 'Kovid Goyal'
supported_platforms = ['windows', 'osx', 'linux']
description = 'A demonstration of the plugin interface for the ebook editor'
minimum_calibre_version = (1, 46, 0)
A single editor plugin can provide multiple tools each tool corresponds to a single button in the toolbar and entry in the
Plugins menu in the editor. These can have sub-menus in case the tool has multiple related actions.
The tools must all be dened in the le main.py in your plugin. Every tool is a class that inherits from the calibre.
gui2.tweak_book.plugin.Tool (page 387) class. Let’s look at main.py from the demo plugin, the source
code is heavily commented and should be self-explanatory. Read the API documents of the calibre.gui2.
tweak_book.plugin.Tool (page 387) class for more details.
100
https://calibre-ebook.com/downloads/editor_demo_plugin.zip
236 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
main.py
Here we will see the denition of a single tool that will multiply all font sizes in the book by a number provided by the
user. This tool demonstrates various important concepts that you will need in developing your own plugins, so you should
read the (heavily commented) source code carefully.
import re
from calibre import force_unicode
from calibre.ebooks.oeb.polish.container import OEB_DOCS, OEB_STYLES, serialize
from calibre.gui2 import error_dialog
# The base class that all tools must inherit from
from calibre.gui2.tweak_book.plugin import Tool
from css_parser.css import CSSRule
from qt.core import QAction, QInputDialog
class DemoTool(Tool):
#: Set this to a unique name it will be used as a key
name = 'demo-tool'
#: If True the user can choose to place this tool in the plugins toolbar
allowed_in_toolbar = True
#: If True the user can choose to place this tool in the plugins menu
allowed_in_menu = True
def create_action(self, for_toolbar=True):
# Create an action, this will be added to the plugins toolbar and
# the plugins menu
ac = QAction(get_icons('images/icon.png'), 'Magnify fonts', self.gui) # noqa
if not for_toolbar:
# Register a keyboard shortcut for this toolbar action. We only
# register it for the action created for the menu, not the toolbar,
# to avoid a double trigger
self.register_shortcut(ac, 'magnify-fonts-tool', default_keys=(
,'Ctrl+Shift+Alt+D',))
ac.triggered.connect(self.ask_user)
return ac
def ask_user(self):
# Ask the user for a factor by which to multiply all font sizes
factor, ok = QInputDialog.getDouble(
self.gui, 'Enter a magnification factor', 'Allow font sizes in the book
,will be multiplied by the specified factor',
value=2, min=0.1, max=4
)
if ok:
# Ensure any in progress editing the user is doing is present in the
,container
self.boss.commit_all_editors_to_container()
try:
self.magnify_fonts(factor)
except Exception:
# Something bad happened report the error to the user
import traceback
(continues on next page)
10.5. Writing your own plugins to extend calibre’s functionality 237
calibre User Manual, Release 7.19.0
(continued from previous page)
error_dialog(self.gui, _('Failed to magnify fonts'), _(
'Failed to magnify fonts, click "Show details" for more info'),
det_msg=traceback.format_exc(), show=True)
# Revert to the saved restore point
self.boss.revert_requested(self.boss.global_undo.previous_container)
else:
# Show the user what changes we have made, allowing her to
# revert them if necessary
self.boss.show_current_diff()
# Update the editor UI to take into account all the changes we
# have made
self.boss.apply_container_update_to_gui()
def magnify_fonts(self, factor):
# Magnify all font sizes defined in the book by the specified factor
# First we create a restore point so that the user can undo all changes
# we make.
self.boss.add_savepoint('Before: Magnify fonts')
container = self.current_container # The book being edited as a container
,object
# Iterate over all style declarations in the book, this means css
# stylesheets, <style> tags and style="" attributes
for name, media_type in container.mime_map.items():
if media_type in OEB_STYLES:
# A stylesheet. Parsed stylesheets are css_parser CSSStylesheet
# objects.
self.magnify_stylesheet(container.parsed(name), factor)
container.dirty(name) # Tell the container that we have changed the
,
stylesheet
elif media_type in OEB_DOCS:
# A HTML file. Parsed HTML files are lxml elements
for style_tag in container.parsed(name).xpath('//*[local-name="style"]
,'):
if style_tag.text and style_tag.get('type', None) in {None, 'text/
,css'}:
# We have an inline CSS <style> tag, parse it into a
# stylesheet object
sheet = container.parse_css(style_tag.text)
self.magnify_stylesheet(sheet, factor)
style_tag.text = serialize(sheet, 'text/css', pretty_
,print=True)
container.dirty(name) # Tell the container that we have
,changed the stylesheet
for elem in container.parsed(name).xpath('//*[@style]'):
# Process inline style attributes
block = container.parse_css(elem.get('style'), is_
,declaration=True)
self.magnify_declaration(block, factor)
elem.set('style', force_unicode(block.getCssText(separator=' '),
,'utf-8'))
def magnify_stylesheet(self, sheet, factor):
# Magnify all fonts in the specified stylesheet by the specified
# factor.
(continues on next page)
238 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
(continued from previous page)
for rule in sheet.cssRules.rulesOfType(CSSRule.STYLE_RULE):
self.magnify_declaration(rule.style, factor)
def magnify_declaration(self, style, factor):
# Magnify all fonts in the specified style declaration by the specified
# factor
val = style.getPropertyValue('font-size')
if not val:
return
# see if the font-size contains a number
num = re.search(r'[0-9.]+', val)
if num is not None:
num = num.group()
val = val.replace(num, '%f' % (float(num) * factor))
style.setProperty('font-size', val)
# We should also be dealing with the font shorthand property and
# font sizes specified as non numbers, but those are left as exercises
# for the reader
Let’s break down main.py. We see that it denes a single tool, named Magnify fonts. This tool will ask the user for a
number and multiply all font sizes in the book by that number.
The rst important thing is the tool name which you must set to some relatively unique string as it will be used as the key
for this tool.
The next important entry point is the calibre.gui2.tweak_book.plugin.Tool.create_action()
(page 388). This method creates the QAction objects that appear in the plugins toolbar and plugin menu. It also, option-
ally, assigns a keyboard shortcut that the user can customize. The triggered signal from the QAction is connected to the
ask_user() method that asks the user for the font size multiplier, and then runs the magnication code.
The magnication code is well commented and fairly simple. The main things to note are that you get a reference to the
editor window as self.gui and the editor Boss as self.boss. The Boss is the object that controls the editor user
interface. It has many useful methods, that are documented in the calibre.gui2.tweak_book.boss.Boss
(page 389) class.
Finally, there is self.current_container which is a reference to the book being edited as a calibre.
ebooks.oeb.polish.container.Container (page 380) object. This represents the book as a collection of
its constituent HTML/CSS/image les and has convenience methods for doing many useful things. The container object
and various useful utility functions that can be reused in your plugin code are documented in API documentation for the
e-book editing tools (page 379).
10.5.4 Adding translations to your plugin
You can have all the user interface strings in your plugin translated and displayed in whatever language is set for the main
calibre user interface.
The rst step is to go through your plugin’s source code and mark all user visible strings as translatable, by surrounding
them in _(). For example:
action_spec = (_('My plugin'), None, _('My plugin is cool'), None)
Then use some program to generate .po les from your plugin source code. There should be one .po le for every language
you want to translate into. For example: de.po for German, fr.po for French and so on. You can use the Poedit
101
program
for this.
101
https://poedit.net/
10.5. Writing your own plugins to extend calibre’s functionality 239
calibre User Manual, Release 7.19.0
Send these .po les to your translators. Once you get them back, compile them into .mo les. You can again use Poedit
for that, or just do:
calibre-debug -c "from calibre.translations.msgfmt import main; main()" filename.po
Put the .mo les into the translations folder in your plugin.
The last step is to simply call the function load_translations() at the top of your plugin’s .py les. For performance reasons
you should only call this function in those .py les that actually have translatable strings. So in a typical User Interface
plugin you would call it at the top of ui.py but not __init__.py.
You can test the translations of your plugins by changing the user interface language in calibre under Prefer-
ences → Interface → Look & feel or by running calibre with the CALIBRE_OVERRIDE_LANG environment variable
set. For example:
CALIBRE_OVERRIDE_LANG=de
Replace de with the language code of the language you want to test.
For translations with plurals, use the ngettext() function instead of _(). For example:
ngettext('Delete a book', 'Delete {} books', num_books).format(num_books)
10.5.5 The plugin API
As you may have noticed above, a plugin in calibre is a class. There are dierent classes for the dierent types of plugins
in calibre. Details on each class, including the base class of all plugins can be found in API documentation for plugins
(page 257).
Your plugin is almost certainly going to use code from calibre. To learn how to nd various bits of functionality in the
calibre code base, read the section on the calibre Code layout (page 362).
10.5.6 Debugging plugins
The rst, most important step is to run calibre in debug mode. You can do this from the command line with:
calibre-debug -g
Or from within calibre by right-clicking the Preferences button or using the Ctrl+Shift+R keyboard shortcut.
When running from the command line, debug output will be printed to the console, when running from within calibre the
output will go to a txt le.
You can insert print statements anywhere in your plugin code, they will be output in debug mode. Remember, this is
Python, you really shouldn’t need anything more than print statements to debug ;) I developed all of calibre using just this
debugging technique.
You can quickly test changes to your plugin by using the following command line:
calibre-debug -s; calibre-customize -b /path/to/your/plugin/folder; calibre
This will shutdown a running calibre, wait for the shutdown to complete, then update your plugin in calibre and relaunch
calibre.
240 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.5.7 More plugin examples
You can nd a list of many sophisticated calibre plugins here
102
.
10.5.8 Sharing your plugins with others
If you would like to share the plugins you have created with other users of calibre, post your plugin in a new thread in the
calibre plugins forum
103
.
10.6 Typesetting mathematics in e-books
The calibre E-book viewer has the ability to display mathematics embedded in e-books (EPUB and HTML les). You
can typeset the mathematics directly with TeX or MathML or AsciiMath. The calibre E-book viewer uses the excellent
MathJax
104
library to do this. This is a brief tutorial on creating e-books with mathematics in them that work well with
the calibre E-book viewer.
10.6.1 A simple HTML le with mathematics
You can write mathematics inline inside a simple HTML le and the calibre E-book viewer will render it into properly
typeset mathematics. In the example below, we use TeX notation for mathematics. You will see that you can use normal
TeX commands, with the small caveat that ampersands and less than and greater than signs have to be written as &amp;
&lt; and &gt; respectively.
The rst step is to tell calibre that this will contains mathematics. You do this by adding the following snippet of code to
the <head> section of the HTML le:
<script type="text/x-mathjax-config"></script>
That’s it, now you can type mathematics just as you would in a .tex le. For example, here are Lorentz’s equations:
<h2>The Lorenz Equations</h2>
<p>
\begin{align}
\dot{x} &amp; = \sigma(y-x) \\
\dot{y} &amp; = \rho x - y - xz \\
\dot{z} &amp; = -\beta z + xy
\end{align}
</p>
This snippet looks like the following screen shot in the calibre E-book viewer.
The complete HTML le, with more equations and inline mathematics is reproduced below. You can convert this HTML
le to EPUB in calibre to end up with an e-book you can distribute easily to other people.
<!DOCTYPE html>
<html>
<!-- Copyright (c) 2012 Design Science, Inc. -->
<head>
(continues on next page)
102
https://www.mobileread.com/forums/showthread.php?t=118764
103
https://www.mobileread.com/forums/forumdisplay.php?f=237
104
https://www.mathjax.org
10.6. Typesetting mathematics in e-books 241
calibre User Manual, Release 7.19.0
Fig. 1: The Lorenz Equations
(continued from previous page)
<title>Math Test Page</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<!-- This script tag is needed to make calibre's ebook-viewer recpgnize that this
,file needs math typesetting -->
<script type="text/x-mathjax-config">
// This line adds numbers to all equations automatically, unless explicitly
,suppressed.
MathJax.tex = {tags: 'all'};
</script>
<style>
h1 {text-align:center}
h2 {
font-weight: bold;
background-color: #DDDDDD;
padding: .2em .5em;
margin-top: 1.5em;
border-top: 3px solid #666666;
border-bottom: 2px solid #999999;
}
</style>
</head>
<body>
<h1>Sample Equations</h1>
<h2>The Lorenz Equations</h2>
<p>
\begin{align}
\dot{x} &amp; = \sigma(y-x) \label{lorenz}\\
\dot{y} &amp; = \rho x - y - xz \\
\dot{z} &amp; = -\beta z + xy
\end{align}
</p>
<h2>The Cauchy-Schwarz Inequality</h2>
<p>\[
\left( \sum_{k=1}^n a_k b_k \right)^{\!\!2} \leq
\left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)
\]</p>
(continues on next page)
242 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
(continued from previous page)
<h2>A Cross Product Formula</h2>
<p>\[
\mathbf{V}_1 \times \mathbf{V}_2 =
\begin{vmatrix}
\mathbf{i} &amp; \mathbf{j} &amp; \mathbf{k} \\
\frac{\partial X}{\partial u} &amp; \frac{\partial Y}{\partial u} &amp; 0 \\
\frac{\partial X}{\partial v} &amp; \frac{\partial Y}{\partial v} &amp; 0 \\
\end{vmatrix}
\]</p>
<h2>The probability of getting \(k\) heads when flipping \(n\) coins is:</h2>
<p>\[P(E) = {n \choose k} p^k (1-p)^{ n-k} \]</p>
<h2>An Identity of Ramanujan</h2>
<p>\[
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} =
1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
{1+\frac{e^{-8\pi}} {1+\ldots} } } }
\]</p>
<h2>A Rogers-Ramanujan Identity</h2>
<p>\[
1 + \frac{q^2}{(1-q)}+\frac{q^6}{(1-q)(1-q^2)}+\cdots =
\prod_{j=0}^{\infty}\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},
\quad\quad \text{for $|q|&lt;1$}.
\]</p>
<h2>Maxwell's Equations</h2>
<p>
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\
,partial t} &amp; = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} &amp; = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\
,partial t} &amp; = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} &amp; = 0
\end{align}
</p>
<h2>Inline Mathematics</h2>
<p>While display equations look good for a page of samples, the
ability to mix math and text in a paragraph is also important. This
expression \(\sqrt{3x-1}+(1+x)^2\) is an example of an inline equation. As
you see, equations can be used this way as well, without unduly
disturbing the spacing between lines.</p>
<h2>References to equations</h2>
<p>Here is a reference to the Lorenz Equations (\ref{lorenz}). Clicking on the
,equation number will take you back to the equation.</p>
(continues on next page)
10.6. Typesetting mathematics in e-books 243
calibre User Manual, Release 7.19.0
(continued from previous page)
</body>
</html>
® Note
The calibre E-book viewer supports MathML as well as TeX, but you must include the <script type="text/
x-mathjax-config"></script> line in your HTML le otherwise the MathML will not render.
10.6.2 More information
Since the calibre E-book viewer uses the MathJax library to render mathematics, the best place to nd out more about
mathematics in e-books and get help is the MathJax website
105
.
10.7 Creating AZW3 EPUB MOBI catalogs
calibre’s Create catalog feature enables you to create a catalog of your library in a variety of formats. This help le
describes cataloging options when generating a catalog in AZW3, EPUB and MOBI formats.
Selecting books to catalog (page 244)
Included sections (page 245)
Prexes (page 246)
Excluded books (page 246)
Excluded genres (page 247)
Other options (page 247)
Custom catalog covers (page 248)
Additional help resources (page 249)
10.7.1 Selecting books to catalog
If you want all of your library cataloged, remove any search or ltering criteria in the main window. With a single book
selected, all books in your library will be candidates for inclusion in the generated catalog. Individual books may be
excluded by various criteria; see the Excluded genres (page 247) section below for more information.
If you want only some of your library cataloged, you have two options:
Create a multiple selection of the books you want cataloged. With more than one book selected in calibre’s main
window, only the selected books will be cataloged.
Use the Search eld or the Tag browser to lter the displayed books. Only the displayed books will be cataloged.
105
https://www.mathjax.org
244 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
To begin catalog generation, select the menu item Convert books > Create a catalog of the books in your calibre library.
You may also add a Create catalog button to a toolbar in Preferences > Interface > Toolbars & menus for easier access to
the Generate catalog dialog.
In Catalog options, select AZW3, EPUB or MOBI as the Catalog format. In the Catalog title eld, provide a name that
will be used for the generated catalog. If a catalog of the same name and format already exists, it will be replaced with
the newly-generated catalog.
Enabling Send catalog to device automatically will download the generated catalog to a connected device upon completion.
10.7.2 Included sections
Sections enabled by a checkmark will be included in the generated catalog:
Authors - all books, sorted by author, presented in a list format. Non-series books are listed before series books.
Titles - all books, sorted by title, presented in a list format.
Series - all books that are part of a series, sorted by series, presented in a list format.
Genres - individual genres presented in a list, sorted by Author and Series.
Recently Added - all books, sorted in reverse chronological order. List includes books added in the last 30 days,
then a month-by-month listing of added books.
Descriptions - detailed description page for each book, including a cover thumbnail and comments. Sorted by
author, with non-series books listed before series books.
10.7. Creating AZW3 EPUB MOBI catalogs 245
calibre User Manual, Release 7.19.0
10.7.3 Prexes
Prex rules allow you to add a prex to book listings when certain criteria are met. For example, you might want to mark
books you’ve read with a checkmark, or books on your wishlist with an X.
The checkbox in the rst column enables the rule. Name is a rule name that you provide. Field is either Tags or a custom
column from your library. Value is the content of Field to match. When a prex rule is satised, the book will be marked
with the selected Prex.
Three prex rules have been specied in the example above:
1. Read book species that a book with any date in a custom column named Last read will be prexed with a checkmark
symbol.
2. Wishlist item species that any book with a Wishlist tag will be prexed with an X symbol.
3. Library books species that any book with a value of True (or Yes) in a custom column Available in Library will
be prexed with a double arrow symbol.
The rst matching rule supplies the prex. Disabled or incomplete rules are ignored.
10.7.4 Excluded books
Exclusion rules allow you to specify books that will not be cataloged.
The checkbox in the rst column enables the rule. Name is a rule name that you provide. Field is either Tags or a custom
column in your library. Value is the content of Field to match. When an exclusion rule is satised, the book will be
excluded from the generated catalog.
Two exclusion rules have been specied in the example above:
1. The Catalogs rule species that any book with a Catalog tag will be excluded from the generated catalog.
246 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
2. The Archived Books rule species that any book with a value of Archived in the custom column Status will be
excluded from the generated catalog.
All rules are evaluated for every book. Disabled or incomplete rules are ignored.
10.7.5 Excluded genres
When the catalog is generated, tags in your database are used as genres. For example, you may use the tags Fiction
and Nonfiction. These tags become genres in the generated catalog, with books listed under their respective genre
lists based on their assigned tags. A book will be listed in every genre section for which it has a corresponding tag.
You may be using certain tags for other purposes, perhaps a + to indicate a read book, or a bracketed tag like [Amazon
Freebie] to indicate a book’s source. The Excluded genres regex allows you to specify tags that you don’t want used as
genres in the generated catalog. The default exclusion regex pattern \[.+\]\+ excludes any tags of the form [tag],
as well as excluding +, the default tag for read books, from being used as genres in the generated catalog.
You can also use an exact tag name in a regex. For example, [Amazon Freebie] or [Project Gutenberg]. If
you want to list multiple exact tags for exclusion, put a pipe (vertical bar) character between them: [Amazon Free-
bie]|[Project Gutenberg].
Results of regex shows you which tags will be excluded when the catalog is built, based on the tags in your database and
the regex pattern you enter. The results are updated as you modify the regex pattern.
10.7.6 Other options
Catalog cover species whether to generate a new cover or use an existing cover. It is possible to create a custom cover
for your catalogs - see Custom catalog covers (page 248) for more information. If you have created a custom cover that
you want to reuse, select Use existing cover. Otherwise, select Generate new cover.
Extra Description note species a custom column’s contents to be inserted into the Description page, next to the cover
thumbnail. For example, you might want to display the date you last read a book using a Last Read custom column. For
advanced use of the Description note feature, see this post in the calibre forum
106
.
Thumb width species a width preference for cover thumbnails included with Descriptions pages. Thumbnails are cached
to improve performance. To experiment with dierent widths, try generating a catalog with just a few books until you’ve
106
https://www.mobileread.com/forums/showpost.php?p=1335767&postcount=395
10.7. Creating AZW3 EPUB MOBI catalogs 247
calibre User Manual, Release 7.19.0
determined your preferred width, then generate your full catalog. The rst time a catalog is generated with a new thumbnail
width, performance will be slower, but subsequent builds of the catalog will take advantage of the thumbnail cache.
Merge with comments species a custom column whose content will be non-destructively merged with the comments
metadata during catalog generation. For example, you might have a custom column Author bio that you’d like to append
to the comments metadata. You can choose to insert the custom column contents before or after the comments section,
and optionally separate the appended content with a horizontal rule separator. Eligible custom column types include
text, comments, and composite.
10.7.7 Custom catalog covers
With the Generate Cover plugin
107
installed, you can create custom
covers for your catalog. To install the plugin, go to Preferences > Advanced > Plugins > Get new plugins.
107
https://www.mobileread.com/forums/showthread.php?t=124219
248 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.7.8 Additional help resources
For more information on calibre’s Catalog feature, see the MobileRead forum sticky Creating Catalogs - Start here
108
,
where you can nd information on how to customize the catalog templates, and how to submit a bug report.
To ask questions or discuss calibre’s Catalog feature with other users, visit the MobileRead forum Library Management
109
.
10.8 Virtual libraries
In calibre, a Virtual library is a way to tell calibre to open only a subset of a normal library. For example, you might want
to only work with books by a certain author, or books having only a certain tag. Using Virtual libraries is the preferred
way of partitioning your large book collection into smaller sub collections. It is superior to splitting up your library into
multiple smaller libraries as, when you want to search through your entire collection, you can simply go back to the full
library. There is no way to search through multiple separate libraries simultaneously in calibre.
A Virtual library is dierent from a simple search. A search will only restrict the list of books shown in the book list. A
Virtual library does that, and in addition it also restricts the entries shown in the Tag browser to the left. The Tag browser
will only show tags, authors, series, publishers, etc. that come from the books in the Virtual library. A Virtual library
thus behaves as though the actual library contains only the restricted set of books.
10.8.1 Creating Virtual libraries
To use a Virtual library click the Virtual library button located to the left of the Search
bar and select the Create Virtual library option. As a rst example, let’s create a Virtual library that shows us only the
books by a particular author. Click the Authors link as shown in the image below and choose the author you want to use
and click OK.
The Create Virtual library dialog has been lled in for you. Click OK and you will see that a new Virtual library has been
created, and automatically switched to, that displays only the books by the selected author. As far as calibre is concerned,
it is as if your library contains only the books by the selected author.
108
https://www.mobileread.com/forums/showthread.php?t=118556
109
https://www.mobileread.com/forums/forumdisplay.php?f=236
10.8. Virtual libraries 249
calibre User Manual, Release 7.19.0
You can switch back to the full library at any time by once again clicking the Virtual library and selecting the entry named
<None>.
Virtual libraries are based on searches. You can use any search as the basis of a Virtual library. The Virtual library will
contain only the books matched by that search. First, type in the search you want to use in the Search bar or build a search
using the Tag browser. When you are happy with the returned results, click the Virtual library button, choose Create
library and enter a name for the new Virtual library. The Virtual library will then be created based on the search you just
typed in. Searches are very powerful, for examples of the kinds of things you can do with them, see The search interface
(page 12).
Examples of useful Virtual libraries
Books added to calibre in the last day::
date:>1daysago
Books added to calibre in the last month::
date:>30daysago
Books with a rating of 5 stars::
rating:5
Books with a rating of at least 4 stars::
rating:>=4
Books with no rating::
rating:false
Periodicals downloaded by the Fetch News function in calibre::
tags:=News and author:=calibre
Books with no tags::
tags:false
Books with no covers::
cover:false
10.8.2 Working with Virtual libraries
You can edit a previously created Virtual library or remove it, by clicking the Virtual library and choosing the appropriate
action.
You can tell calibre that you always want to apply a particular Virtual library when the current library is opened, by going
to Preferences → Interface → Behavior.
You can quickly use the current search as a temporary Virtual library by clicking the Virtual library button and choosing
the *current search entry.
You can display all available Virtual libraries as tabs above the book list. This is particularly handy if you like switching
between Virtual libraries very often. Click the Virtual library button and select Show Virtual libraries as tabs. You can
re-arrange the tabs by drag and drop and close ones you do not want to see. Closed tabs can be restored by right-clicking
on the tab bar.
250 Chapter 10. Tutorials
calibre User Manual, Release 7.19.0
10.8.3 Using Virtual libraries in searches
You can search for books that are in a Virtual library using the vl: prex. For example, vl:Read will nd all the
books in the Read Virtual library. The search vl:Read and vl:"Science Fiction" will nd all the books
that are in both the
Read
and
Science Fiction
Virtual libraries.
The value following vl: must be the name of a Virtual library. If the Virtual library name contains spaces then surround
it with quotes.
One use for a Virtual library search is in the Content server. In Preferences → Sharing over the net → Require username and
password you can limit the calibre libraries visible to a user. For each visible library you can specify a search expression
to further limit which books are seen. Use
vl:"Virtual library name"
to limit the books to those in a Virtual
library.
10.8.4 Using additional restrictions
You can further restrict the books shown in a Virtual library by using Additional restrictions. An additional restriction is
saved search you previously created that can be applied to the current Virtual library to further restrict the books shown
in a Virtual library. For example, say you have a Virtual library for books tagged as Historical Fiction and a saved search
that shows you unread books, you can click the Virtual Library button and choose the Additional restriction option to show
only unread Historical Fiction books. To learn about saved searches, see Saving searches (page 18).
10.8. Virtual libraries 251
calibre User Manual, Release 7.19.0
252 Chapter 10. Tutorials
CHAPTER
ELEVEN
THE CALIBRE:// URL SCHEME
calibre registers itself as the handler program for calibre:// URLs. So you can use these to perform actions like opening
books, searching for books, etc from other programs/documents or via the command line. For example, running the
following at the command line:
calibre calibre://switch-library/Some_Library
Will open calibre with the library named Some Library. Library names are the folder name of the library folder
with spaces replaced by underscores. The special value _ means the current library. The various types of URLs are
documented below.
You can even place these links inside HTML les or Word documents or similar and the operating system will automati-
cally run calibre to perform the specied action.
Switch to a specic library (page 253)
Show a specic book in calibre (page 254)
Open a specic book in the E-book viewer at a specic position (page 254)
Searching for books (page 254)
Open a book details window on a book in some library (page 255)
Open the notes associated with an author/series/etc. (page 255)
Hex encoding of URL parameters (page 255)
11.1 Switch to a specic library
The URL syntax is:
calibre://switch-library/Library_Name
Library names are the folder name of the library with spaces replaced by underscores. The special value _ means the
current library. You can also use hex encoding (page 255) for the library names, useful if the library names have special
characters that would otherwise require URL encoding. Hex encoded library names look like:
_hex_-AD23F4BC
Where the part after the _hex_- prex is the library name encoded as UTF-8 and every byte represented by two hex-
adecimal characters.
253
calibre User Manual, Release 7.19.0
11.2 Show a specic book in calibre
The URL syntax is:
calibre://show-book/Library_Name/book_id
This will show the book with book_id (a number) in calibre. The ids for books can be seen in the calibre interface by
hovering over the Click to open link in the Book details panel, it is the number in brackets at the end of the path to the
book folder.
You can copy a link to the current book displayed in calibre by right clicking the Book details panel and choosing Copy
link to book.
If a search is active and the book is not matched by the search then the search is cleared.
If a Virtual library is selected, calibre will use it when showing the book. If the book isn’t found in that virtual library
then the virtual library is cleared.
If you want to switch to a particular Virtual library when showing the book, use:
calibre://show-book/Library_Name/book_id?virtual_library=Library%20Name
or
calibre://show-book/Library_Name/book_id?encoded_virtual_library=hex_encoded_virtual_
,library_name
replacing spaces in the Virtual library name by %20. If the book isn’t found in that virtual library then the virtual library
is ignored.
11.3 Open a specic book in the E-book viewer at a specic position
The URL syntax is:
calibre://view-book/Library_Name/book_id/book_format?open_at=location
Here, book_format is the format of the book, for example, EPUB or MOBI and the location is an optional location
inside the book. The easiest way to get these links is to open a book in the viewer, then in the viewer controls select Go
to → Location and there such a link will be given that you can copy/paste elsewhere.
11.4 Searching for books
The URL syntax is:
calibre://search/Library_Name?q=query
calibre://search/Library_Name?eq=hex_encoded_query
Here query is any valid search expression (page 12). If the search expression is complicated, encode it as a hex string
(page 255) and use eq instead. Leaving out the query will cause the current search to be cleared.
By default, if a Virtual library is selected, calibre will clear it before doing the search to ensure all books are found. If
you want to preserve the Virtual library, use:
calibre://search/Library_Name?q=query&virtual_library=_
If you want to switch to a particular Virtual library, use:
254 Chapter 11. The calibre:// URL scheme
calibre User Manual, Release 7.19.0
calibre://search/Library_Name?virtual_library=Library%20Name
or
calibre://search/Library_Name?encoded_virtual_library=hex_encoded_virtual_library_name
replacing spaces in the Virtual library name by %20.
If you perform a search in calibre and want to generate a link for it you can do so by right clicking the search bar and
choosing Copy search as URL.
11.5 Open a book details window on a book in some library
The URL syntax is:
calibre://book-details/Library_Name/book_id
This opens a book details window on the specied book from the specied library without changing the current library
or the selected book.
11.6 Open the notes associated with an author/series/etc.
The URL syntax is:
calibre://book-details/Library_Name/Field_Name/id_Item_Id
This opens a window showing the notes of the specied item. The easiest way to create such URLs is to show the notes
you want in calibre and click the Copy URL button to copy the URL to the clipboard and paste it wherever you need.
Here Field_Name is the name of the columns such as authors or tags. For user created columns, replace the
leading # in the eld name with an underscore, so #mytags becomes _mytags.
In addition to specifying items by id using Item_Id you can also specify them by name using either val_Item_Name
or
hex_Hex_Encoded_Item_Name
. For example:
calibre://book-details/Library_Name/authors/val_John%20Doe
11.7 Hex encoding of URL parameters
Hex encoding of URL parameters is done by rst encoding the parameter as UTF-8 bytes, and then replacing each byte
by two hexadecimal characters representing the byte. For example, the string abc is the bytes 0x61 0x62 and 0x63
in UTF-8, so the encoded version is the string: 616263.
11.5. Open a book details window on a book in some library 255
calibre User Manual, Release 7.19.0
256 Chapter 11. The calibre:// URL scheme
CHAPTER
TWELVE
CUSTOMIZING CALIBRE
calibre has a highly modular design. Various parts of it can be customized. Here, you will learn:
how to use environment variables and tweaks to customize calibre’s behavior,
how to specify your own static resources like icons and templates to override the defaults
how to use plugins to add functionality to calibre.
how to share icon themes and plugins with other calibre users.
to see how to create recipes to add new sources of online content to calibre visit the Section Adding your favorite
news website (page 31).
® Note
Note that although icon themes and plugins are indexed and downloadable via calibre’s builtin updater, they are not
part of calibre, and their canonical locations for support and source code are on the Mobileread forums
110
in their
support threads.
Environment variables (page 290)
Tweaks (page 291)
Overriding icons, templates, et cetera (page 301)
Creating your own icon theme for calibre (page 302)
Customizing calibre with plugins (page 302)
12.1 API documentation for plugins
Denes various abstract base classes that can be subclassed to create powerful plugins. The useful classes are:
Plugin (page 258)
FileTypePlugin (page 260)
110
https://www.mobileread.com/forums/forumdisplay.php?f=166
257
calibre User Manual, Release 7.19.0
Metadata plugins (page 262)
Catalog plugins (page 263)
Metadata download plugins (page 264)
Conversion plugins (page 267)
Device drivers (page 270)
User interface actions (page 284)
Preferences plugins (page 287)
12.1.1 Plugin
class calibre.customize.Plugin(plugin_path)
A calibre plugin. Useful members include:
self.installation_type: Stores how the plugin was installed.
self.plugin_path: Stores path to the ZIP le that contains
this plugin or None if it is a builtin plugin
self.site_customization: Stores a customization string entered
by the user.
Methods that should be overridden in sub classes:
initialize() (page 259)
customization_help() (page 260)
Useful methods:
temporary_file() (page 260)
__enter__()
load_resources() (page 259)
supported_platforms = []
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
name = 'Trivial Plugin'
The name of this plugin. You must set it something other than Trivial Plugin for it to work.
version = (1, 0, 0)
The version of this plugin as a 3-tuple (major, minor, revision)
description = 'Does absolutely nothing'
A short string describing what this plugin does
author = 'Unknown'
The author of this plugin
priority = 1
When more than one plugin exists for a letype, the plugins are run in order of decreasing priority. Plugins
with higher priority will be run rst. The highest possible priority is sys.maxsize. Default priority is 1.
258 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
minimum_calibre_version = (0, 4, 118)
The earliest version of calibre this plugin requires
installation_type = None
The way this plugin is installed
can_be_disabled = True
If False, the user will not be able to disable this plugin. Use with care.
type = 'Base'
The type of this plugin. Used for categorizing plugins in the GUI
initialize()
Called once when calibre plugins are initialized. Plugins are re-initialized every time a new plugin is added.
Also note that if the plugin is run in a worker process, such as for adding books, then the plugin will be
initialized for every new worker process.
Perform any plugin specic initialization here, such as extracting resources from the plugin ZIP le. The path
to the ZIP le is available as self.plugin_path.
Note that self.site_customization is not available at this point.
config_widget()
Implement this method and save_settings() (page 259) in your plugin to use a custom conguration
dialog, rather then relying on the simple string based default customization.
This method, if implemented, must return a QWidget. The widget can have an optional method validate()
that takes no arguments and is called immediately after the user clicks OK. Changes are applied if and only
if the method returns True.
If for some reason you cannot perform the conguration at this time, return a tuple of two strings (message,
details), these will be displayed as a warning dialog to the user and the process will be aborted.
save_settings(cong_widget)
Save the settings specied by the user with cong_widget.
Parameters
config_widget The widget returned by config_widget() (page 259).
do_user_config(parent=None)
This method shows a conguration dialog for this plugin. It returns True if the user clicks OK, False otherwise.
The changes are automatically applied.
load_resources(names)
If this plugin comes in a ZIP le (user added plugin), this method will allow you to load resources from the
ZIP le.
For example to load an image:
pixmap = QPixmap()
pixmap.loadFromData(self.load_resources(['images/icon.png'])['images/icon.png
,'])
icon = QIcon(pixmap)
Parameters
names List of paths to resources in the ZIP le using / as separator
Returns
A dictionary of the form {name: file_contents}. Any names that were not found in
the ZIP le will not be present in the dictionary.
12.1. API documentation for plugins 259
calibre User Manual, Release 7.19.0
customization_help(gui=False)
Return a string giving help on how to customize this plugin. By default raise a NotImplementedError,
which indicates that the plugin does not require customization.
If you re-implement this method in your subclass, the user will be asked to enter a string as customization for
this plugin. The customization string will be available as self.site_customization.
Site customization could be anything, for example, the path to a needed binary on the user’s computer.
Parameters
gui If True return HTML help, otherwise return plain text help.
temporary_file(sux)
Return a le-like object that is a temporary le on the le system. This le will remain available even after
being closed and will only be removed on interpreter shutdown. Use the name member of the returned object
to access the full path to the created temporary le.
Parameters
suffix The sux that the temporary le will have.
cli_main(args)
This method is the main entry point for your plugins command line interface. It is called when the user does:
calibre-debug -r “Plugin Name”. Any arguments passed are present in the args variable.
12.1.2 FileTypePlugin
class calibre.customize.FileTypePlugin(plugin_path)
Bases: Plugin (page 258)
A plugin that is associated with a particular set of le types.
file_types = {}
Set of le types for which this plugin should be run. Use ‘*’ for all le types. For example: {'lit',
'mobi', 'prc'}
on_import = False
If True, this plugin is run when books are added to the database
on_postimport = False
If True, this plugin is run after books are added to the database. In this case the postimport and postadd
methods of the plugin are called.
on_postconvert = False
If True, this plugin is run after a book is converted. In this case the postconvert method of the plugin is called.
on_postdelete = False
If True, this plugin is run after a book le is deleted from the database. In this case the postdelete method of
the plugin is called.
on_preprocess = False
If True, this plugin is run just before a conversion
on_postprocess = False
If True, this plugin is run after conversion on the nal le produced by the conversion output plugin.
type = 'File type'
The type of this plugin. Used for categorizing plugins in the GUI
260 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
run(path_to_ebook)
Run the plugin. Must be implemented in subclasses. It should perform whatever modications are required
on the e-book and return the absolute path to the modied e-book. If no modications are needed, it should
return the path to the original e-book. If an error is encountered it should raise an Exception. The default
implementation simply return the path to the original e-book. Note that the path to the original le (before
any le type plugins are run, is available as self.original_path_to_le).
The modied e-book le should be created with the temporary_file() method.
Parameters
path_to_ebook Absolute path to the e-book.
Returns
Absolute path to the modied e-book.
postimport(book_id, book_format, db)
Called post import, i.e., after the book le has been added to the database. Note that this is dierent from
postadd() (page 261) which is called when the book record is created for the rst time. This method is
called whenever a new le is added to a book record. It is useful for modifying the book record based on the
contents of the newly added le.
Parameters
book_id Database id of the added book.
book_format The le type of the book that was added.
db Library database.
postconvert(book_id, book_format, db)
Called post conversion, i.e., after the conversion output book le has been added to the database. Note that
it is run after a conversion only, not after a book is added. It is useful for modifying the book record based
on the contents of the newly added le.
Parameters
book_id Database id of the added book.
book_format The le type of the book that was added.
db Library database.
postdelete(book_id, book_format, db)
Called post deletion, i.e., after the book le has been deleted from the database. Note that it is not run when
a book record is deleted, only when one or more formats from the book are deleted. It is useful for modifying
the book record based on the format of the deleted le.
Parameters
book_id Database id of the added book.
book_format The le type of the book that was added.
db Library database.
postadd(book_id, fmt_map, db)
Called post add, i.e. after a book has been added to the db. Note that this is dierent from postimport()
(page 261), which is called after a single book le has been added to a book. postadd() is called only when
an entire book record with possibly more than one book le has been created for the rst time. This is useful
if you wish to modify the book record in the database when the book is rst added to calibre.
Parameters
12.1. API documentation for plugins 261
calibre User Manual, Release 7.19.0
book_id Database id of the added book.
fmt_map Map of le format to path from which the le format was added. Note that this
might or might not point to an actual existing le, as sometimes les are added as streams.
In which case it might be a dummy value or a non-existent path.
db Library database
12.1.3 Metadata plugins
class calibre.customize.MetadataReaderPlugin(*args, **kwargs)
Bases: Plugin (page 258)
A plugin that implements reading metadata from a set of le types.
file_types = {}
Set of le types for which this plugin should be run. For example: set(['lit', 'mobi', 'prc'])
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
version = (7, 19, 0)
The version of this plugin as a 3-tuple (major, minor, revision)
author = 'Kovid Goyal'
The author of this plugin
type = 'Metadata reader'
The type of this plugin. Used for categorizing plugins in the GUI
get_metadata(stream, type)
Return metadata for the le represented by stream (a le like object that supports reading). Raise an exception
when there is an error with the input data.
Parameters
type The type of le. Guaranteed to be one of the entries in file_types (page 262).
Returns
A calibre.ebooks.metadata.book.Metadata object
class calibre.customize.MetadataWriterPlugin(*args, **kwargs)
Bases: Plugin (page 258)
A plugin that implements reading metadata from a set of le types.
file_types = {}
Set of le types for which this plugin should be run. For example: set(['lit', 'mobi', 'prc'])
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
version = (7, 19, 0)
The version of this plugin as a 3-tuple (major, minor, revision)
author = 'Kovid Goyal'
The author of this plugin
262 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
type = 'Metadata writer'
The type of this plugin. Used for categorizing plugins in the GUI
set_metadata(stream, mi, type)
Set metadata for the le represented by stream (a le like object that supports reading). Raise an exception
when there is an error with the input data.
Parameters
type The type of le. Guaranteed to be one of the entries in file_types (page 262).
mi A calibre.ebooks.metadata.book.Metadata object
12.1.4 Catalog plugins
class calibre.customize.CatalogPlugin(plugin_path)
Bases: Plugin (page 258)
A plugin that implements a catalog generator.
file_types = {}
Output le type for which this plugin should be run. For example: ‘epub’ or ‘xml’
type = 'Catalog generator'
The type of this plugin. Used for categorizing plugins in the GUI
cli_options = []
CLI parser options specic to this plugin, declared as namedtuple Option:
from collections import namedtuple Option = namedtuple(‘Option’, ‘option, default, dest, help’) cli_options
= [Option(’–catalog-title’, default = ‘My Catalog’, dest = ‘catalog_title’, help = (_(‘Title of generated catalog.
nDefault:’) + ‘” + ‘%default’ + “’”))] cli_options parsed in calibre.db.cli.cmd_catalog:option_parser()
initialize()
If plugin is not a built-in, copy the plugin’s .ui and .py les from the ZIP le to $TMPDIR. Tab will be
dynamically generated and added to the Catalog Options dialog in calibre.gui2.dialogs.catalog.py:Catalog
run(path_to_output, opts, db, ids, notication=None)
Run the plugin. Must be implemented in subclasses. It should generate the catalog in the format specied in
le_types, returning the absolute path to the generated catalog le. If an error is encountered it should raise
an Exception.
The generated catalog le should be created with the temporary_file() method.
Parameters
path_to_output Absolute path to the generated catalog le.
opts A dictionary of keyword arguments
db A LibraryDatabase2 object
12.1. API documentation for plugins 263
calibre User Manual, Release 7.19.0
12.1.5 Metadata download plugins
class calibre.ebooks.metadata.sources.base.Source(*args, **kwargs)
Bases: Plugin (page 258)
type = 'Metadata source'
The type of this plugin. Used for categorizing plugins in the GUI
author = 'Kovid Goyal'
The author of this plugin
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
capabilities = frozenset({})
Set of capabilities supported by this plugin. Useful capabilities are: ‘identify’, ‘cover’
touched_fields = frozenset({})
List of metadata elds that can potentially be download by this plugin during the identify phase
has_html_comments = False
Set this to True if your plugin returns HTML formatted comments
supports_gzip_transfer_encoding = False
Setting this to True means that the browser object will indicate that it supports gzip transfer encoding. This
can speedup downloads but make sure that the source actually supports gzip transfer encoding correctly rst
ignore_ssl_errors = False
Set this to True to ignore HTTPS certicate errors when connecting to this source.
cached_cover_url_is_reliable = True
Cached cover URLs can sometimes be unreliable (i.e. the download could fail or the returned image could
be bogus). If that is often the case with this source, set to False
options = ()
A list of Option objects. They will be used to automatically construct the conguration widget for this
plugin
config_help_message = None
A string that is displayed at the top of the cong widget for this plugin
can_get_multiple_covers = False
If True this source can return multiple covers for a given query
auto_trim_covers = False
If set to True covers downloaded by this plugin are automatically trimmed.
prefer_results_with_isbn = True
If set to True, and this source returns multiple results for a query, some of which have ISBNs and some of
which do not, the results without ISBNs will be ignored
is_configured()
Return False if your plugin needs to be congured before it can be used. For example, it might need a
username/password/API key.
264 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
customization_help()
Return a string giving help on how to customize this plugin. By default raise a NotImplementedError,
which indicates that the plugin does not require customization.
If you re-implement this method in your subclass, the user will be asked to enter a string as customization for
this plugin. The customization string will be available as self.site_customization.
Site customization could be anything, for example, the path to a needed binary on the user’s computer.
Parameters
gui If True return HTML help, otherwise return plain text help.
config_widget()
Implement this method and save_settings() (page 265) in your plugin to use a custom conguration
dialog, rather then relying on the simple string based default customization.
This method, if implemented, must return a QWidget. The widget can have an optional method validate()
that takes no arguments and is called immediately after the user clicks OK. Changes are applied if and only
if the method returns True.
If for some reason you cannot perform the conguration at this time, return a tuple of two strings (message,
details), these will be displayed as a warning dialog to the user and the process will be aborted.
save_settings(cong_widget)
Save the settings specied by the user with cong_widget.
Parameters
config_widget The widget returned by config_widget() (page 265).
get_author_tokens(authors, only_rst_author=True)
Take a list of authors and return a list of tokens useful for an AND search query. This function tries to return
tokens in rst name middle names last name order, by assuming that if a comma is in the author name, the
name is in lastname, other names form.
get_title_tokens(title, strip_joiners=True, strip_subtitle=False)
Take a title and return a list of tokens useful for an AND search query. Excludes connectives(optionally) and
punctuation.
split_jobs(jobs, num)
Split a list of jobs into at most num groups, as evenly as possible
test_fields(mi)
Return the rst eld from self.touched_elds that is null on the mi object
clean_downloaded_metadata(mi)
Call this method in your plugin’s identify method to normalize metadata before putting the Metadata object
into result_queue. You can of course, use a custom algorithm suited to your metadata source.
get_book_url(identiers)
Return a 3-tuple or None. The 3-tuple is of the form: (identier_type, identier_value, URL). The URL
is the URL for the book identied by identiers at this source. identier_type, identier_value specify the
identier corresponding to the URL. This URL must be browsable to by a human using a browser. It is meant
to provide a clickable link for the user to easily visit the books page at this source. If no URL is found, return
None. This method must be quick, and consistent, so only implement it if it is possible to construct the URL
from a known scheme given identiers.
get_book_url_name(idtype, idval, url)
Return a human readable name from the return value of get_book_url().
12.1. API documentation for plugins 265
calibre User Manual, Release 7.19.0
get_book_urls(identiers)
Override this method if you would like to return multiple URLs for this book. Return a list of 3-tuples. By
default this method simply calls get_book_url() (page 265).
get_cached_cover_url(identiers)
Return cached cover URL for the book identied by the identiers dictionary or None if no such URL exists.
Note that this method must only return validated URLs, i.e. not URLS that could result in a generic cover
image or a not found error.
id_from_url(url)
Parse a URL and return a tuple of the form: (identier_type, identier_value). If the URL does not match
the pattern for the metadata source, return None.
identify_results_keygen(title=None, authors=None, identiers={})
Return a function that is used to generate a key that can sort Metadata objects by their relevance given a search
query (title, authors, identiers).
These keys are used to sort the results of a call to identify() (page 266).
For details on the default algorithm see InternalMetadataCompareKeyGen (page 267). Re-
implement this function in your plugin if the default algorithm is not suitable.
identify(log, result_queue, abort, title=None, authors=None, identiers={}, timeout=30)
Identify a book by its Title/Author/ISBN/etc.
If identiers(s) are specied and no match is found and this metadata source does not store all related iden-
tiers (for example, all ISBNs of a book), this method should retry with just the title and author (assuming
they were specied).
If this metadata source also provides covers, the URL to the cover should be cached so that a subsequent call
to the get covers API with the same ISBN/special identier does not need to get the cover URL again. Use
the caching API for this.
Every Metadata object put into result_queue by this method must have a source_relevance attribute that is an
integer indicating the order in which the results were returned by the metadata source for this query. This
integer will be used by compare_identify_results(). If the order is unimportant, set it to zero for
every result.
Make sure that any cover/ISBN mapping information is cached before the Metadata object is put into re-
sult_queue.
Parameters
log A log object, use it to output debugging information/errors
result_queue A result Queue, results should be put into it. Each result is a Metadata
object
abort If abort.is_set() returns True, abort further processing and return as soon as possible
title The title of the book, can be None
authors A list of authors of the book, can be None
identifiers A dictionary of other identiers, most commonly {‘isbn’:’1234…’}
timeout Timeout in seconds, no network request should hang for longer than timeout.
Returns
None if no errors occurred, otherwise a unicode representation of the error suitable for showing
to the user
266 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
download_cover(log, result_queue, abort, title=None, authors=None, identiers={}, timeout=30,
get_best_cover=False)
Download a cover and put it into result_queue. The parameters all have the same meaning as for iden-
tify() (page 266). Put (self, cover_data) into result_queue.
This method should use cached cover URLs for eciency whenever possible. When cached data is not present,
most plugins simply call identify and use its results.
If the parameter get_best_cover is True and this plugin can get multiple covers, it should only get the “best”
one.
class calibre.ebooks.metadata.sources.base.InternalMetadataCompareKeyGen(mi,
source_plugin,
title,
authors,
identi-
ers)
Generate a sort key for comparison of the relevance of Metadata objects, given a search query. This is used only
to compare results from the same metadata source, not across dierent sources.
The sort key ensures that an ascending order sort is a sort by order of decreasing relevance.
The algorithm is:
Prefer results that have at least one identier the same as for the query
Prefer results with a cached cover URL
Prefer results with all available elds lled in
Prefer results with the same language as the current user interface language
Prefer results that are an exact title match to the query
Prefer results with longer comments (greater than 10% longer)
Use the relevance of the result as reported by the metadata source’s search
engine
12.1.6 Conversion plugins
class calibre.customize.conversion.InputFormatPlugin(*args)
Bases: Plugin (page 258)
InputFormatPlugins are responsible for converting a document into HTML+OPF+CSS+etc. The results of the
conversion must be encoded in UTF-8. The main action happens in convert() (page 268).
type = 'Conversion input'
The type of this plugin. Used for categorizing plugins in the GUI
can_be_disabled = False
If False, the user will not be able to disable this plugin. Use with care.
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
file_types = {}
Set of le types for which this plugin should be run For example: set(['azw', 'mobi', 'prc'])
12.1. API documentation for plugins 267
calibre User Manual, Release 7.19.0
is_image_collection = False
If True, this input plugin generates a collection of images, one per HTML le. This can be set dynamically,
in the convert method if the input les can be both image collections and non-image collections. If you set
this to True, you must implement the get_images() method that returns a list of images.
core_usage = 1
Number of CPU cores used by this plugin. A value of -1 means that it uses all available cores
for_viewer = False
If set to True, the input plugin will perform special processing to make its output suitable for viewing
output_encoding = 'utf-8'
The encoding that this input plugin creates les in. A value of None means that the encoding is undened
and must be detected individually
common_options = {<calibre.customize.conversion.OptionRecommendation
object>}
Options shared by all Input format plugins. Do not override in sub-classes. Use options (page 268) instead.
Every option must be an instance of OptionRecommendation.
options = {}
Options to customize the behavior of this plugin. Every option must be an instance of OptionRecommen-
dation.
recommendations = {}
A set of 3-tuples of the form (option_name, recommended_value, recommendation_level)
get_images()
Return a list of absolute paths to the images, if this input plugin represents an image collection. The list of
images is in the same order as the spine and the TOC.
convert(stream, options, le_ext, log, accelerators)
This method must be implemented in sub-classes. It must return the path to the created OPF le or an
OEBBook instance. All output should be contained in the current folder. If this plugin creates les outside
the current folder they must be deleted/marked for deletion before this method returns.
Parameters
stream A le like object that contains the input le.
options Options to customize the conversion process. Guaranteed to have attributes
corresponding to all the options declared by this plugin. In addition, it will have a ver-
bose attribute that takes integral values from zero upwards. Higher numbers mean be more
verbose. Another useful attribute is input_profile that is an instance of calibre.
customize.profiles.InputProfile.
file_ext The extension (without the .) of the input le. It is guaranteed to be one of
the le_types supported by this plugin.
log A calibre.utils.logging.Log object. All output should use this object.
accelerators A dictionary of various information that the input plugin can get easily
that would speed up the subsequent stages of the conversion.
postprocess_book(oeb, opts, log)
Called to allow the input plugin to perform postprocessing after the book has been parsed.
268 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
specialize(oeb, opts, log, output_fmt)
Called to allow the input plugin to specialize the parsed book for a particular output format. Called after
postprocess_book and before any transforms are performed on the parsed book.
gui_configuration_widget(parent, get_option_by_name, get_option_help, db, book_id=None)
Called to create the widget used for conguring this plugin in the calibre GUI. The widget must be an instance
of the PluginWidget class. See the builtin input plugins for examples.
class calibre.customize.conversion.OutputFormatPlugin(*args)
Bases: Plugin (page 258)
OutputFormatPlugins are responsible for converting an OEB document (OPF+HTML) into an output e-book.
The OEB document can be assumed to be encoded in UTF-8. The main action happens in convert() (page 269).
type = 'Conversion output'
The type of this plugin. Used for categorizing plugins in the GUI
can_be_disabled = False
If False, the user will not be able to disable this plugin. Use with care.
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
file_type = None
The le type (extension without leading period) that this plugin outputs
common_options = {<calibre.customize.conversion.OptionRecommendation
object>}
Options shared by all Input format plugins. Do not override in sub-classes. Use options (page 269) instead.
Every option must be an instance of OptionRecommendation.
options = {}
Options to customize the behavior of this plugin. Every option must be an instance of OptionRecommen-
dation.
recommendations = {}
A set of 3-tuples of the form (option_name, recommended_value, recommendation_level)
property description
str(object=’’) -> str str(bytes_or_buer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specied, then the object must
expose a data buer that will be decoded using the given encoding and error handler. Otherwise, returns the
result of object.__str__() (if dened) or repr(object). encoding defaults to sys.getdefaultencoding(). errors
defaults to ‘strict’.
convert(oeb_book, output, input_plugin, opts, log)
Render the contents of oeb_book (which is an instance of calibre.ebooks.oeb.OEBBook) to the le
specied by output.
Parameters
output Either a le like object or a string. If it is a string it is the path to a folder that
may or may not exist. The output plugin should write its output into that folder. If it is a le
like object, the output plugin should write its output into the le.
input_plugin The input plugin that was used at the beginning of the conversion
pipeline.
12.1. API documentation for plugins 269
calibre User Manual, Release 7.19.0
opts Conversion options. Guaranteed to have attributes corresponding to the OptionRec-
ommendations of this plugin.
log The logger. Print debug/info messages etc. using this.
specialize_options(log, opts, input_fmt)
Can be used to change the values of conversion options, as used by the conversion pipeline.
specialize_css_for_output(log, opts, item, stylizer)
Can be used to make changes to the CSS during the CSS attening process.
Parameters
item The item (HTML le) being processed
stylizer A Stylizer object containing the attened styles for item. You can get the style
for any element by stylizer.style(element).
gui_configuration_widget(parent, get_option_by_name, get_option_help, db, book_id=None)
Called to create the widget used for conguring this plugin in the calibre GUI. The widget must be an instance
of the PluginWidget class. See the builtin output plugins for examples.
12.1.7 Device drivers
The base class for all device drivers is DevicePlugin (page 270). However, if your device exposes itself as a USBMS
drive to the operating system, you should use the USBMS class instead as it implements all the logic needed to support
these kinds of devices.
class calibre.devices.interface.DevicePlugin(plugin_path)
Bases: Plugin (page 258)
Denes the interface that should be implemented by backends that communicate with an e-book reader.
type = 'Device interface'
The type of this plugin. Used for categorizing plugins in the GUI
FORMATS = ['lrf', 'rtf', 'pdf', 'txt']
Ordered list of supported formats
VENDOR_ID = 0
VENDOR_ID can be either an integer, a list of integers or a dictionary If it is a dictionary, it must be a
dictionary of dictionaries, of the form:
{
integer_vendor_id : { product_id : [list of BCDs], ... },
...
}
PRODUCT_ID = 0
An integer or a list of integers
BCD = None
BCD can be either None to not distinguish between devices based on BCD, or it can be a list of the BCD
numbers of all devices supported by this driver.
THUMBNAIL_HEIGHT = 68
Height for thumbnails on the device
270 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
THUMBNAIL_COMPRESSION_QUALITY = 75
Compression quality for thumbnails. Set this closer to 100 to have better quality thumbnails with fewer
compression artifacts. Of course, the thumbnails get larger as well.
WANTS_UPDATED_THUMBNAILS = False
Set this to True if the device supports updating cover thumbnails during sync_booklists. Setting it to true will
ask device.py to refresh the cover thumbnails during book matching
CAN_SET_METADATA = ['title', 'authors', 'collections']
Whether the metadata on books can be set via the GUI.
CAN_DO_DEVICE_DB_PLUGBOARD = False
Whether the device can handle device_db metadata plugboards
path_sep = '/'
Path separator for paths to books on device
icon = 'reader.png'
Icon for this device
UserAnnotation
alias of Annotation
OPEN_FEEDBACK_MESSAGE = None
GUI displays this as a message if not None in the status bar. Useful if opening can take a long time
VIRTUAL_BOOK_EXTENSIONS = frozenset({})
Set of extensions that are “virtual books” on the device and therefore cannot be viewed/saved/added to library.
For example: frozenset(['kobo'])
VIRTUAL_BOOK_EXTENSION_MESSAGE = None
Message to display to user for virtual book extensions.
NUKE_COMMENTS = None
Whether to nuke comments in the copy of the book sent to the device. If not None this should be short string
that the comments will be replaced by.
MANAGES_DEVICE_PRESENCE = False
If True indicates that this driver completely manages device detection, ejecting and so forth. If you set this
to True, you must implement the detect_managed_devices and debug_managed_device_detection methods.
A driver with this set to true is responsible for detection of devices, managing a blacklist of devices, a list
of ejected devices and so forth. calibre will periodically call the detect_managed_devices() method and if it
returns a detected device, calibre will call open(). open() will be called every time a device is returned even if
previous calls to open() failed, therefore the driver must maintain its own blacklist of failed devices. Similarly,
when ejecting, calibre will call eject() and then assuming the next call to detect_managed_devices() returns
None, it will call post_yank_cleanup().
SLOW_DRIVEINFO = False
If set the True, calibre will call the get_driveinfo() (page 273) method after the books lists have been
loaded to get the driveinfo.
ASK_TO_ALLOW_CONNECT = False
If set to True, calibre will ask the user if they want to manage the device with calibre, the rst time it
is detected. If you set this to True you must implement get_device_uid() (page 276) and ig-
nore_connected_device() (page 276) and get_user_blacklisted_devices() (page 276)
and set_user_blacklisted_devices() (page 276)
12.1. API documentation for plugins 271
calibre User Manual, Release 7.19.0
user_feedback_after_callback = None
Set this to a dictionary of the form {‘title’:title, ‘msg’:msg, ‘det_msg’:detailed_msg} to have calibre popup a
message to the user after some callbacks are run (currently only upload_books). Be careful to not spam the
user with too many messages. This variable is checked after every callback, so only set it when you really
need to.
classmethod get_open_popup_message()
GUI displays this as a non-modal popup. Should be an instance of OpenPopupMessage
is_usb_connected(devices_on_system, debug=False, only_presence=False)
Return True, device_info if a device handled by this plugin is currently connected.
Parameters
devices_on_system List of devices currently connected
detect_managed_devices(devices_on_system, force_refresh=False)
Called only if MANAGES_DEVICE_PRESENCE is True.
Scan for devices that this driver can handle. Should return a device object if a device is found. This object will
be passed to the open() method as the connected_device. If no device is found, return None. The returned
object can be anything, calibre does not use it, it is only passed to open().
This method is called periodically by the GUI, so make sure it is not too resource intensive. Use a cache to
avoid repeatedly scanning the system.
Parameters
devices_on_system Set of USB devices found on the system.
force_refresh If True and the driver uses a cache to prevent repeated scanning, the
cache must be ushed.
debug_managed_device_detection(devices_on_system, output)
Called only if MANAGES_DEVICE_PRESENCE is True.
Should write information about the devices detected on the system to output, which is a le like object.
Should return True if a device was detected and successfully opened, otherwise False.
reset(key='-1', log_packets=False, report_progress=None, detected_device=None)
Parameters
key The key to unlock the device
log_packets If true the packet stream to/from the device is logged
report_progress Function that is called with a % progress (number between 0 and
100) for various tasks. If it is called with -1 that means that the task does not have any
progress information
detected_device Device information from the device scanner
can_handle_windows(usbdevice, debug=False)
Optional method to perform further checks on a device to see if this driver is capable of handling it. If it is
not it should return False. This method is only called after the vendor, product ids and the bcd have matched,
so it can do some relatively time intensive checks. The default implementation returns True. This method is
called only on Windows. See also can_handle() (page 273).
Note that for devices based on USBMS this method by default delegates to can_handle() (page 273). So
you only need to override can_handle() (page 273) in your subclass of USBMS.
272 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
Parameters
usbdevice A usbdevice as returned by calibre.devices.winusb.
scan_usb_devices()
can_handle(device_info, debug=False)
Unix version of can_handle_windows() (page 272).
Parameters
device_info Is a tuple of (vid, pid, bcd, manufacturer, product, serial number)
open(connected_device, library_uuid)
Perform any device specic initialization. Called after the device is detected but before any other functions
that communicate with the device. For example: For devices that present themselves as USB Mass storage
devices, this method would be responsible for mounting the device or if the device has been automounted, for
nding out where it has been mounted. The method calibre.devices.usbms.device.Device.
open() (page 281) has an implementation of this function that should serve as a good example for USB
Mass storage devices.
This method can raise an OpenFeedback exception to display a message to the user.
Parameters
connected_device The device that we are trying to open. It is a tuple of (vendor id,
product id, bcd, manufacturer name, product name, device serial number). However, some
devices have no serial number and on Windows only the rst three elds are present, the rest
are None.
library_uuid The UUID of the current calibre library. Can be None if there is no
library (for example when used from the command line).
eject()
Un-mount / eject the device from the OS. This does not check if there are pending GUI jobs that need to
communicate with the device.
NOTE: That this method may not be called on the same thread as the rest of the device methods.
post_yank_cleanup()
Called if the user yanks the device without ejecting it rst.
set_progress_reporter(report_progress)
Set a function to report progress information.
Parameters
report_progress Function that is called with a % progress (number between 0 and
100) for various tasks. If it is called with -1 that means that the task does not have any progress
information
get_device_information(end_session=True)
Ask device for device information. See L{DeviceInfoQuery}.
Returns
(device name, device version, software version on device, MIME type) The tuple can optionally
have a fth element, which is a drive information dictionary. See usbms.driver for an example.
get_driveinfo()
Return the driveinfo dictionary. Usually called from get_device_information(), but if loading the driveinfo is
slow for this driver, then it should set SLOW_DRIVEINFO. In this case, this method will be called by calibre
after the book lists have been loaded. Note that it is not called on the device thread, so the driver should cache
the drive info in the books() method and this function should return the cached data.
12.1. API documentation for plugins 273
calibre User Manual, Release 7.19.0
card_prefix(end_session=True)
Return a 2 element list of the prex to paths on the cards. If no card is present None is set for the card’s
prex. E.G. (‘/place’, ‘/place2’) (None, ‘place2’) (‘place’, None) (None, None)
total_space(end_session=True)
Get total space available on the mountpoints:
1. Main memory
2. Memory Card A
3. Memory Card B
Returns
A 3 element list with total space in bytes of (1, 2, 3). If a particular device doesn’t have any of
these locations it should return 0.
free_space(end_session=True)
Get free space available on the mountpoints:
1. Main memory
2. Card A
3. Card B
Returns
A 3 element list with free space in bytes of (1, 2, 3). If a particular device doesn’t have any of
these locations it should return -1.
books(oncard=None, end_session=True)
Return a list of e-books on the device.
Parameters
oncard If ‘carda’ or ‘cardb’ return a list of e-books on the specic storage card, otherwise
return list of e-books in main memory of device. If a card is specied and no books are on the
card return empty list.
Returns
A BookList.
upload_books(les, names, on_card=None, end_session=True, metadata=None)
Upload a list of books to the device. If a le already exists on the device, it should be replaced. This
method should raise a FreeSpaceError if there is not enough free space on the device. The text of the
FreeSpaceError must contain the word “card” if on_card is not None otherwise it must contain the word
“memory”.
Parameters
files A list of paths
names A list of le names that the books should have once uploaded to the device.
len(names) == len(les)
metadata If not None, it is a list of Metadata objects. The idea is to use the metadata
to determine where on the device to put the book. len(metadata) == len(les). Apart from the
regular cover (path to cover), there may also be a thumbnail attribute, which should be used
in preference. The thumbnail attribute is of the form (width, height, cover_data as jpeg).
274 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
Returns
A list of 3-element tuples. The list is meant to be passed to add_books_to_metadata()
(page 275).
classmethod add_books_to_metadata(locations, metadata, booklists)
Add locations to the booklists. This function must not communicate with the device.
Parameters
locations Result of a call to L{upload_books}
metadata List of Metadata objects, same as for upload_books() (page 274).
booklists A tuple containing the result of calls to (books(oncard=None)(),
books(oncard='carda')(), :meth`books(oncard=’cardb’)`).
delete_books(paths, end_session=True)
Delete books at paths on device.
classmethod remove_books_from_metadata(paths, booklists)
Remove books from the metadata list. This function must not communicate with the device.
Parameters
paths paths to books on the device.
booklists A tuple containing the result of calls to (books(oncard=None)(),
books(oncard='carda')(), :meth`books(oncard=’cardb’)`).
sync_booklists(booklists, end_session=True)
Update metadata on device.
Parameters
booklists A tuple containing the result of calls to (books(oncard=None)(),
books(oncard='carda')(), :meth`books(oncard=’cardb’)`).
get_file(path, outle, end_session=True)
Read the le at path on the device and write it to outle.
Parameters
outfile le object like sys.stdout or the result of an open() (page 273) call.
classmethod config_widget()
Should return a QWidget. The QWidget contains the settings for the device interface
classmethod save_settings(settings_widget)
Should save settings to disk. Takes the widget created in config_widget() (page 275) and saves all
settings to disk.
classmethod settings()
Should return an opts object. The opts object should have at least one attribute format_map which is an
ordered list of formats for the device.
set_plugboards(plugboards, pb_func)
provide the driver the current set of plugboards and a function to select a specic plugboard. This method is
called immediately before add_books and sync_booklists.
pb_func is a callable with the following signature::
def pb_func(device_name, format, plugboards)
12.1. API documentation for plugins 275
calibre User Manual, Release 7.19.0
You give it the current device name (either the class name or DEVICE_PLUGBOARD_NAME), the for-
mat you are interested in (a ‘real’ format or ‘device_db’), and the plugboards (you were given those by
set_plugboards, the same place you got this method).
Returns
None or a single plugboard instance.
set_driveinfo_name(location_code, name)
Set the device name in the driveinfo le to ‘name’. This setting will persist until the le is re-created or the
name is changed again.
Non-disk devices should implement this method based on the location codes returned by the
get_device_information() method.
prepare_addable_books(paths)
Given a list of paths, returns another list of paths. These paths point to addable versions of the books.
If there is an error preparing a book, then instead of a path, the position in the returned list for that book
should be a three tuple: (original_path, the exception instance, traceback)
startup()
Called when calibre is starting the device. Do any initialization required. Note that multiple instances of the
class can be instantiated, and thus __init__ can be called multiple times, but only one instance will have this
method called. This method is called on the device thread, not the GUI thread.
shutdown()
Called when calibre is shutting down, either for good or in preparation to restart. Do any cleanup required.
This method is called on the device thread, not the GUI thread.
get_device_uid()
Must return a unique id for the currently connected device (this is called immediately after a successful call
to open()). You must implement this method if you set ASK_TO_ALLOW_CONNECT = True
ignore_connected_device(uid)
Should ignore the device identied by uid (the result of a call to get_device_uid()) in the future. You must
implement this method if you set ASK_TO_ALLOW_CONNECT = True. Note that this function is called
immediately after open(), so if open() caches some state, the driver should reset that state.
get_user_blacklisted_devices()
Return map of device uid to friendly name for all devices that the user has asked to be ignored.
set_user_blacklisted_devices(devices)
Set the list of device uids that should be ignored by this driver.
specialize_global_preferences(device_prefs)
Implement this method if your device wants to override a particular preference. You must ensure that all call
sites that want a preference that can be overridden use device_prefs[‘something’] instead of prefs[‘something’].
Your method should call device_prefs.set_overrides(pref=val, pref=val, …). Currently used for: metadata
management (prefs[‘manage_device_metadata’])
set_library_info(library_name, library_uuid, eld_metadata)
Implement this method if you want information about the current calibre library. This method is called at
startup and when the calibre library changes while connected.
is_dynamically_controllable()
Called by the device manager when starting plugins. If this method returns a string, then a) it supports the
device manager’s dynamic control interface, and b) that name is to be used when talking to the plugin.
This method can be called on the GUI thread. A driver that implements this method must be thread safe.
276 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
start_plugin()
This method is called to start the plugin. The plugin should begin to accept device connections however it
does that. If the plugin is already accepting connections, then do nothing.
This method can be called on the GUI thread. A driver that implements this method must be thread safe.
stop_plugin()
This method is called to stop the plugin. The plugin should no longer accept connections, and should cleanup
behind itself. It is likely that this method should call shutdown. If the plugin is already not accepting connec-
tions, then do nothing.
This method can be called on the GUI thread. A driver that implements this method must be thread safe.
get_option(opt_string, default=None)
Return the value of the option indicated by opt_string. This method can be called when the plugin is not
started. Return None if the option does not exist.
This method can be called on the GUI thread. A driver that implements this method must be thread safe.
set_option(opt_string, opt_value)
Set the value of the option indicated by opt_string. This method can be called when the plugin is not started.
This method can be called on the GUI thread. A driver that implements this method must be thread safe.
is_running()
Return True if the plugin is started, otherwise false
This method can be called on the GUI thread. A driver that implements this method must be thread safe.
synchronize_with_db(db, book_id, book_metadata, rst_call)
Called during book matching when a book on the device is matched with a book in calibre’s db. The method
is responsible for synchronizing data from the device to calibre’s db (if needed).
The method must return a two-value tuple. The rst value is a set of calibre book ids changed if calibre’s
database was changed or None if the database was not changed. If the rst value is an empty set then the
metadata for the book on the device is updated with calibre’s metadata and given back to the device, but no
GUI refresh of that book is done. This is useful when the calibre data is correct but must be sent to the device.
The second value is itself a 2-value tuple. The rst value in the tuple species whether a book format should
be sent to the device. The intent is to permit verifying that the book on the device is the same as the book in
calibre. This value must be None if no book is to be sent, otherwise return the base le name on the device (a
string like foobar.epub). Be sure to include the extension in the name. The device subsystem will construct a
send_books job for all books with not- None returned values. Note: other than to later retrieve the extension,
the name is ignored in cases where the device uses a template to generate the le name, which most do. The
second value in the returned tuple indicated whether the format is future-dated. Return True if it is, otherwise
return False. calibre will display a dialog to the user listing all future dated books.
Extremely important: this method is called on the GUI thread. It must be threadsafe with respect to the
device manager’s thread.
book_id: the calibre id for the book in the database. book_metadata: the Metadata object for the book
coming from the device. rst_call: True if this is the rst call during a sync, False otherwise
class calibre.devices.interface.BookList(oncard, prex, settings)
Bases:
list
A list of books. Each Book object must have the elds
1. title
2. authors
12.1. API documentation for plugins 277
calibre User Manual, Release 7.19.0
3. size (le size of the book)
4. datetime (a UTC time tuple)
5. path (path on the device to the book)
6. thumbnail (can be None) thumbnail is either a str/bytes object with the image data or it should have an attribute
image_path that stores an absolute (platform native) path to the image
7. tags (a list of strings, can be empty).
supports_collections()
Return True if the device supports collections for this book list.
add_book(book, replace_metadata)
Add the book to the booklist. Intent is to maintain any device-internal metadata. Return True if booklists
must be sync’ed
remove_book(book)
Remove a book from the booklist. Correct any device metadata at the same time
get_collections(collection_attributes)
Return a dictionary of collections created from collection_attributes. Each entry in the dictionary is of the
form collection name:[list of books]
The list of books is sorted by book title, except for collections created from series, in which case series_index
is used.
Parameters
collection_attributes A list of attributes of the Book object
USB Mass Storage based devices
The base class for such devices is calibre.devices.usbms.driver.USBMS (page 281). This class in turn
inherits some of its functionality from its bases, documented below. A typical basic USBMS based driver looks like this:
from calibre.devices.usbms.driver import USBMS
class PDNOVEL(USBMS):
name = 'Pandigital Novel device interface'
gui_name = 'PD Novel'
description = _('Communicate with the Pandigital Novel')
author = 'Kovid Goyal'
supported_platforms = ['windows', 'linux', 'osx']
FORMATS = ['epub', 'pdf']
VENDOR_ID = [0x18d1]
PRODUCT_ID = [0xb004]
BCD = [0x224]
THUMBNAIL_HEIGHT = 144
EBOOK_DIR_MAIN = 'eBooks'
SUPPORTS_SUB_DIRS = False
def upload_cover(self, path, filename, metadata):
coverdata = getattr(metadata, 'thumbnail', None)
if coverdata and coverdata[2]:
(continues on next page)
278 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
(continued from previous page)
with open('%s.jpg' % os.path.join(path, filename), 'wb') as coverfile:
coverfile.write(coverdata[2])
class calibre.devices.usbms.device.Device(plugin_path)
Bases: DeviceConfig, DevicePlugin (page 270)
This class provides logic common to all drivers for devices that export themselves as USB Mass Storage devices.
Provides implementations for mounting/ejecting of USBMS devices on all platforms.
VENDOR_ID = 0
VENDOR_ID can be either an integer, a list of integers or a dictionary If it is a dictionary, it must be a
dictionary of dictionaries, of the form:
{
integer_vendor_id : { product_id : [list of BCDs], ... },
...
}
PRODUCT_ID = 0
An integer or a list of integers
BCD = None
BCD can be either None to not distinguish between devices based on BCD, or it can be a list of the BCD
numbers of all devices supported by this driver.
WINDOWS_MAIN_MEM = None
String identifying the main memory of the device in the Windows PnP id strings This can be None, string,
list of strings or compiled regex
WINDOWS_CARD_A_MEM = None
String identifying the rst card of the device in the Windows PnP id strings This can be None, string, list of
strings or compiled regex
WINDOWS_CARD_B_MEM = None
String identifying the second card of the device in the Windows PnP id strings This can be None, string, list
of strings or compiled regex
OSX_MAIN_MEM_VOL_PAT = None
Used by the new driver detection to disambiguate main memory from storage cards. Should be a regular
expression that matches the main memory mount point assigned by macOS
BACKLOADING_ERROR_MESSAGE = None
MAX_PATH_LEN = 250
The maximum length of paths created on the device
NEWS_IN_FOLDER = True
Put news in its own folder
reset(key='-1', log_packets=False, report_progress=None, detected_device=None)
Parameters
key
The key to unlock the device
log_packets If true the packet stream to/from the device is logged
12.1. API documentation for plugins 279
calibre User Manual, Release 7.19.0
report_progress Function that is called with a % progress (number between 0 and
100) for various tasks. If it is called with -1 that means that the task does not have any
progress information
detected_device Device information from the device scanner
set_progress_reporter(report_progress)
Set a function to report progress information.
Parameters
report_progress Function that is called with a % progress (number between 0 and
100) for various tasks. If it is called with -1 that means that the task does not have any progress
information
card_prefix(end_session=True)
Return a 2 element list of the prex to paths on the cards. If no card is present None is set for the card’s
prex. E.G. (‘/place’, ‘/place2’) (None, ‘place2’) (‘place’, None) (None, None)
total_space(end_session=True)
Get total space available on the mountpoints:
1. Main memory
2. Memory Card A
3. Memory Card B
Returns
A 3 element list with total space in bytes of (1, 2, 3). If a particular device doesn’t have any of
these locations it should return 0.
free_space(end_session=True)
Get free space available on the mountpoints:
1. Main memory
2. Card A
3. Card B
Returns
A 3 element list with free space in bytes of (1, 2, 3). If a particular device doesn’t have any of
these locations it should return -1.
windows_sort_drives(drives)
Called to disambiguate main memory and storage card for devices that do not distinguish between them on
the basis of WINDOWS_CARD_NAME. For example: The EB600
can_handle_windows(usbdevice, debug=False)
Optional method to perform further checks on a device to see if this driver is capable of handling it. If it is
not it should return False. This method is only called after the vendor, product ids and the bcd have matched,
so it can do some relatively time intensive checks. The default implementation returns True. This method is
called only on Windows. See also can_handle().
Note that for devices based on USBMS this method by default delegates to can_handle(). So you only
need to override can_handle() in your subclass of USBMS.
280 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
Parameters
usbdevice A usbdevice as returned by calibre.devices.winusb.
scan_usb_devices()
open(connected_device, library_uuid)
Perform any device specic initialization. Called after the device is detected but before any other functions
that communicate with the device. For example: For devices that present themselves as USB Mass storage
devices, this method would be responsible for mounting the device or if the device has been automounted, for
nding out where it has been mounted. The method calibre.devices.usbms.device.Device.
open() (page 281) has an implementation of this function that should serve as a good example for USB
Mass storage devices.
This method can raise an OpenFeedback exception to display a message to the user.
Parameters
connected_device The device that we are trying to open. It is a tuple of (vendor id,
product id, bcd, manufacturer name, product name, device serial number). However, some
devices have no serial number and on Windows only the rst three elds are present, the rest
are None.
library_uuid The UUID of the current calibre library. Can be None if there is no
library (for example when used from the command line).
eject()
Un-mount / eject the device from the OS. This does not check if there are pending GUI jobs that need to
communicate with the device.
NOTE: That this method may not be called on the same thread as the rest of the device methods.
post_yank_cleanup()
Called if the user yanks the device without ejecting it rst.
sanitize_callback(path)
Callback to allow individual device drivers to override the path sanitization used by cre-
ate_upload_path().
filename_callback(default, mi)
Callback to allow drivers to change the default le name set by create_upload_path().
sanitize_path_components(components)
Perform any device specic sanitization on the path components for les to be uploaded to the device
get_annotations(path_map)
Resolve path_map to annotation_map of les found on the device
add_annotation_to_library(db, db_id, annotation)
Add an annotation to the calibre library
class calibre.devices.usbms.cli.CLI
class calibre.devices.usbms.driver.USBMS(plugin_path)
Bases: CLI (page 281), Device (page 279)
The base class for all USBMS devices. Implements the logic for sending/getting/updating metadata/caching meta-
data/etc.
description = 'Communicate with an e-book reader.'
A short string describing what this plugin does
12.1. API documentation for plugins 281
calibre User Manual, Release 7.19.0
author = 'John Schember'
The author of this plugin
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
booklist_class
alias of BookList
book_class
alias of Book
FORMATS = []
Ordered list of supported formats
CAN_SET_METADATA = []
Whether the metadata on books can be set via the GUI.
get_device_information(end_session=True)
Ask device for device information. See L{DeviceInfoQuery}.
Returns
(device name, device version, software version on device, MIME type) The tuple can optionally
have a fth element, which is a drive information dictionary. See usbms.driver for an example.
set_driveinfo_name(location_code, name)
Set the device name in the driveinfo le to ‘name’. This setting will persist until the le is re-created or the
name is changed again.
Non-disk devices should implement this method based on the location codes returned by the
get_device_information() method.
books(oncard=None, end_session=True)
Return a list of e-books on the device.
Parameters
oncard If ‘carda’ or ‘cardb’ return a list of e-books on the specic storage card, otherwise
return list of e-books in main memory of device. If a card is specied and no books are on the
card return empty list.
Returns
A BookList.
upload_books(les, names, on_card=None, end_session=True, metadata=None)
Upload a list of books to the device. If a le already exists on the device, it should be replaced. This
method should raise a FreeSpaceError if there is not enough free space on the device. The text of the
FreeSpaceError must contain the word “card” if on_card is not None otherwise it must contain the word
“memory”.
Parameters
files A list of paths
names A list of le names that the books should have once uploaded to the device.
len(names) == len(les)
metadata If not None, it is a list of Metadata objects. The idea is to use the metadata
to determine where on the device to put the book. len(metadata) == len(les). Apart from the
regular cover (path to cover), there may also be a thumbnail attribute, which should be used
in preference. The thumbnail attribute is of the form (width, height, cover_data as jpeg).
282 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
Returns
A list of 3-element tuples. The list is meant to be passed to add_books_to_metadata()
(page 283).
upload_cover(path, lename, metadata, lepath)
Upload book cover to the device. Default implementation does nothing.
Parameters
path The full path to the folder where the associated book is located.
filename The name of the book le without the extension.
metadata metadata belonging to the book. Use metadata.thumbnail for cover
filepath The full path to the e-book le
add_books_to_metadata(locations, metadata, booklists)
Add locations to the booklists. This function must not communicate with the device.
Parameters
locations Result of a call to L{upload_books}
metadata List of Metadata objects, same as for upload_books() (page 282).
booklists A tuple containing the result of calls to (books(oncard=None)(),
books(oncard='carda')(), :meth`books(oncard=’cardb’)`).
delete_books(paths, end_session=True)
Delete books at paths on device.
remove_books_from_metadata(paths, booklists)
Remove books from the metadata list. This function must not communicate with the device.
Parameters
paths paths to books on the device.
booklists A tuple containing the result of calls to (books(oncard=None)(),
books(oncard='carda')(), :meth`books(oncard=’cardb’)`).
sync_booklists(booklists, end_session=True)
Update metadata on device.
Parameters
booklists A tuple containing the result of calls to (books(oncard=None)(),
books(oncard='carda')(), :meth`books(oncard=’cardb’)`).
classmethod normalize_path(path)
Return path with platform native path separators
12.1. API documentation for plugins 283
calibre User Manual, Release 7.19.0
12.1.8 User interface actions
If you are adding your own plugin in a ZIP le, you should subclass both InterfaceActionBase and InterfaceAction. The
load_actual_plugin() method of your InterfaceActionBase subclass must return an instantiated object of your
InterfaceBase subclass.
class calibre.gui2.actions.InterfaceAction(parent, site_customization)
Bases: QObject
A plugin representing an “action” that can be taken in the graphical user interface. All the items in the toolbar and
context menus are implemented by these plugins.
Note that this class is the base class for these plugins, however, to integrate the plugin with calibre’s plugin system,
you have to make a wrapper class that references the actual plugin. See the calibre.customize.builtins
module for examples.
If two InterfaceAction (page 284) objects have the same name, the one with higher priority takes precedence.
Sub-classes should implement the genesis() (page 286), library_changed() (page 286), loca-
tion_selected() (page 286), shutting_down() (page 287), initialization_complete()
(page 286) and tag_browser_context_action() (page 286) methods.
Once initialized, this plugin has access to the main calibre GUI via the gui member. You can access other plugins
by name, for example:
self.gui.iactions['Save To Disk']
To access the actual plugin, use the interface_action_base_plugin attribute, this attribute only be-
comes available after the plugin has been initialized. Useful if you want to use methods from the plugin class like
do_user_cong().
The QAction specied by action_spec (page 284) is automatically create and made available as self.
qaction.
name = 'Implement me'
The plugin name. If two plugins with the same name are present, the one with higher priority takes precedence.
priority = 1
The plugin priority. If two plugins with the same name are present, the one with higher priority takes prece-
dence.
popup_type = 1
The menu popup type for when this plugin is added to a toolbar
auto_repeat = False
Whether this action should be auto repeated when its shortcut key is held down.
action_spec = ('text', 'icon', None, None)
Of the form: (text, icon_path, tooltip, keyboard shortcut). icon, tooltip and keyboard shortcut can be None.
keyboard shortcut must be either a string, None or tuple of shortcuts. If None, a keyboard shortcut corre-
sponding to the action is not registered. If you pass an empty tuple, then the shortcut is registered with no
default key binding.
action_shortcut_name = None
If not None, used for the name displayed to the user when customizing the keyboard shortcuts for the above
action spec instead of action_spec[0]
action_add_menu = False
If True, a menu is automatically created and added to self.qaction
284 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
action_menu_clone_qaction = False
If True, a clone of self.qaction is added to the menu of self.qaction If you want the text of this action to be
dierent from that of self.qaction, set this variable to the new text
dont_add_to = frozenset({})
Set of locations to which this action must not be added. See all_locations for a list of possible locations
dont_remove_from = frozenset({})
Set of locations from which this action must not be removed. See all_locations for a list of possible
locations
action_type = 'global'
Type of action ‘current’ means acts on the current view ‘global’ means an action that does not act on the current
view, but rather on calibre as a whole
accepts_drops = False
If True, then this InterfaceAction will have the opportunity to interact with drag and drop events. See the
methods, accept_enter_event() (page 285), :meth`:accept_drag_move_event`, drop_event()
(page 285) for details.
accept_enter_event(event, mime_data)
This method should return True i this interface action is capable of handling the drag event. Do not call
accept/ignore on the event, that will be taken care of by the calibre UI.
accept_drag_move_event(event, mime_data)
This method should return True i this interface action is capable of handling the drag event. Do not call
accept/ignore on the event, that will be taken care of by the calibre UI.
drop_event(event, mime_data)
This method should perform some useful action and return True i this interface action is capable of handling
the drop event. Do not call accept/ignore on the event, that will be taken care of by the calibre UI. You should
not perform blocking/long operations in this function. Instead emit a signal or use QTimer.singleShot and
return quickly. See the builtin actions for examples.
create_menu_action(menu, unique_name, text, icon=None, shortcut=None, description=None,
triggered=None, shortcut_name=None, persist_shortcut=False)
Convenience method to easily add actions to a QMenu. Returns the created QAction. This action has one
extra attribute calibre_shortcut_unique_name which if not None refers to the unique name under which this
action is registered with the keyboard manager.
Parameters
menu The QMenu the newly created action will be added to
unique_name A unique name for this action, this must be globally unique, so make it
as descriptive as possible. If in doubt, add an UUID to it.
text The text of the action.
icon Either a QIcon or a le name. The le name is passed to the QIcon.ic() builtin, so
you do not need to pass the full path to the images folder.
shortcut A string, a list of strings, None or False. If False, no keyboard shortcut is reg-
istered for this action. If None, a keyboard shortcut with no default keybinding is registered.
String and list of strings register a shortcut with default keybinding as specied.
description A description for this action. Used to set tooltips.
triggered A callable which is connected to the triggered signal of the created action.
12.1. API documentation for plugins 285
calibre User Manual, Release 7.19.0
shortcut_name The text displayed to the user when customizing the keyboard shortcuts
for this action. By default it is set to the value of text.
persist_shortcut – Shortcuts for actions that don’t always appear, or are li-
brary dependent, may disappear when other keyboard shortcuts are edited unless `per-
sist_shortcut` is set True.
load_resources(names)
If this plugin comes in a ZIP le (user added plugin), this method will allow you to load resources from the
ZIP le.
For example to load an image:
pixmap = QPixmap()
pixmap.loadFromData(tuple(self.load_resources(['images/icon.png']).
,values())[0])
icon = QIcon(pixmap)
Parameters
names List of paths to resources in the ZIP le using / as separator
Returns
A dictionary of the form {name : file_contents}. Any names that were not found in
the ZIP le will not be present in the dictionary.
genesis()
Setup this plugin. Only called once during initialization. self.gui is available. The action specied by ac-
tion_spec (page 284) is available as self.qaction.
location_selected(loc)
Called whenever the book list being displayed in calibre changes. Currently values for loc are: library,
main, card and cardb.
This method should enable/disable this action and its sub actions as appropriate for the location.
library_about_to_change(olddb, db)
Called whenever the current library is changed.
Parameters
olddb The LibraryDatabase corresponding to the previous library.
db The LibraryDatabase corresponding to the new library.
library_changed(db)
Called whenever the current library is changed.
Parameters
db The LibraryDatabase corresponding to the current library.
gui_layout_complete()
Called once per action when the layout of the main GUI is completed. If your action needs to make changes
to the layout, they should be done here, rather than in initialization_complete() (page 286).
initialization_complete()
Called once per action when the initialization of the main GUI is completed.
286 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
tag_browser_context_action(index)
Called when displaying the context menu in the Tag browser. index is the QModelIndex that points to
the Tag browser item that was right clicked. Test it for validity with index.valid() and get the underlying
TagTreeItem object with index.data(Qt.ItemDataRole.UserRole). Any action objects yielded by this method
will be added to the context menu.
shutting_down()
Called once per plugin when the main GUI is in the process of shutting down. Release any used resources,
but try not to block the shutdown for long periods of time.
class calibre.customize.InterfaceActionBase(*args, **kwargs)
Bases: Plugin (page 258)
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
author = 'Kovid Goyal'
The author of this plugin
type = 'User interface action'
The type of this plugin. Used for categorizing plugins in the GUI
can_be_disabled = False
If False, the user will not be able to disable this plugin. Use with care.
load_actual_plugin(gui)
This method must return the actual interface action plugin object.
12.1.9 Preferences plugins
class calibre.customize.PreferencesPlugin(plugin_path)
Bases: Plugin (page 258)
A plugin representing a widget displayed in the Preferences dialog.
This plugin has only one important method create_widget() (page 288). The various elds of the plugin
control how it is categorized in the UI.
supported_platforms = ['windows', 'osx', 'linux']
List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']
author = 'Kovid Goyal'
The author of this plugin
type = 'Preferences'
The type of this plugin. Used for categorizing plugins in the GUI
can_be_disabled = False
If False, the user will not be able to disable this plugin. Use with care.
config_widget = None
Import path to module that contains a class named CongWidget which implements the CongWidgetInter-
face. Used by create_widget() (page 288).
category_order = 100
Where in the list of categories the category (page 288) of this plugin should be.
12.1. API documentation for plugins 287
calibre User Manual, Release 7.19.0
name_order = 100
Where in the list of names in a category, the gui_name (page 288) of this plugin should be
category = None
The category this plugin should be in
gui_category = None
The category name displayed to the user for this plugin
gui_name = None
The name displayed to the user for this plugin
icon = None
The icon for this plugin, should be an absolute path
description = None
The description used for tooltips and the like
create_widget(parent=None)
Create and return the actual Qt widget used for setting this group of preferences. The widget must implement
the calibre.gui2.preferences.ConfigWidgetInterface (page 288).
The default implementation uses config_widget (page 287) to instantiate the widget.
class calibre.gui2.preferences.ConfigWidgetInterface
This class denes the interface that all widgets displayed in the Preferences dialog must implement. See Config-
WidgetBase (page 289) for a base class that implements this interface and denes various convenience methods
as well.
changed_signal = None
This signal must be emitted whenever the user changes a value in this widget
supports_restoring_to_defaults = True
Set to True i the restore_to_defaults() method is implemented.
restore_defaults_desc = 'Restore settings to default values. You have to
click Apply to actually save the default settings.'
The tooltip for the “Restore defaults” button
restart_critical = False
If True the Preferences dialog will not allow the user to set any more preferences. Only has eect if com-
mit() (page 288) returns True.
genesis(gui)
Called once before the widget is displayed, should perform any necessary setup.
Parameters
gui The main calibre graphical user interface
initialize()
Should set all cong values to their initial values (the values stored in the cong les). A “return” statement
is optional. Return False if the dialog is not to be shown.
restore_defaults()
Should set all cong values to their defaults.
288 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
commit()
Save any changed settings. Return True if the changes require a restart, False otherwise. Raise an Abort-
Commit exception to indicate that an error occurred. You are responsible for giving the user feedback about
what the error is and how to correct it.
refresh_gui(gui)
Called once after this widget is committed. Responsible for causing the gui to reread any changed settings.
Note that by default the GUI re-initializes various elements anyway, so most widgets won’t need to use this
method.
initial_tab_changed()
Called if the initially displayed tab is changed before the widget is shown, but after it is initialized.
class
calibre.gui2.preferences.
ConfigWidgetBase
(
parent=None
)
Base class that contains code to easily add standard cong widgets like checkboxes, combo boxes, text elds and
so on. See the register() (page 289) method.
This class automatically handles change notication, resetting to default, translation between gui objects and cong
objects, etc. for registered settings.
If your cong widget inherits from this class but includes setting that are not registered, you should override the
ConfigWidgetInterface (page 288) methods and call the base class methods inside the overrides.
changed_signal
This signal must be emitted whenever the user changes a value in this widget
supports_restoring_to_defaults = True
Set to True i the restore_to_defaults() method is implemented.
restart_critical = False
If True the Preferences dialog will not allow the user to set any more preferences. Only has eect if com-
mit() (page 289) returns True.
register(name, cong_obj, gui_name=None, choices=None, restart_required=False,
empty_string_is_None=True, setting=<class 'calibre.gui2.preferences.Setting'>)
Register a setting.
Parameters
name The setting name
config_obj The cong object that reads/writes the setting
gui_name The name of the GUI object that presents an interface to change the setting.
By default it is assumed to be 'opt_' + name.
choices If this setting is a multiple choice (combobox) based setting, the list of choices.
The list is a list of two element tuples of the form: [(gui name, value), ...]
setting The class responsible for managing this setting. The default class handles almost
all cases, so this param is rarely used.
initialize()
Should set all cong values to their initial values (the values stored in the cong les). A “return” statement
is optional. Return False if the dialog is not to be shown.
commit(*args)
Save any changed settings. Return True if the changes require a restart, False otherwise. Raise an Abort-
Commit exception to indicate that an error occurred. You are responsible for giving the user feedback about
what the error is and how to correct it.
12.1. API documentation for plugins 289
calibre User Manual, Release 7.19.0
restore_defaults(*args)
Should set all cong values to their defaults.
12.2 Environment variables
CALIBRE_CONFIG_DIRECTORY - sets the folder where conguration les are stored/read.
CALIBRE_TEMP_DIR - sets the temporary folder used by calibre
CALIBRE_CACHE_DIRECTORY - sets the folder calibre uses to cache persistent data between sessions
CALIBRE_OVERRIDE_DATABASE_PATH - allows you to specify the full path to metadata.db. Using this vari-
able you can have metadata.db be in a location other than the library folder. Useful if your library folder is on a
networked drive that does not support le locking.
CALIBRE_DEVELOP_FROM - used to run from a calibre development environment. See Setting up a calibre
development environment (page 361).
CALIBRE_OVERRIDE_LANG - used to force the language used by the interface (ISO 639 language code)
CALIBRE_TEST_TRANSLATION - used to test a translation .po le (should be the path to the .po le)
CALIBRE_NO_NATIVE_FILEDIALOGS - causes calibre to not use native le dialogs for selecting les/folders.
CALIBRE_NO_NATIVE_MENUBAR - causes calibre to not create a native (global) menu on Ubuntu Unity and
similar Linux desktop environments. The menu is instead placed inside the window, as is traditional.
CALIBRE_USE_SYSTEM_THEME - by default, on Linux, calibre uses its own builtin Qt style. This is to avoid
crashes and hangs caused by incompatibilities between the version of Qt calibre is built against and the system Qt.
The downside is that calibre may not follow the system look and feel. If you set this environment variable on Linux,
it will cause calibre to use the system theme beware of crashes and hangs.
CALIBRE_SHOW_DEPRECATION_WARNINGS - causes calibre to print deprecation warnings to stdout. Useful
for calibre developers.
CALIBRE_NO_DEFAULT_PROGRAMS - prevent calibre from automatically registering the letypes it is capable
of handling with Windows.
QT_QPA_PLATFORM - On Linux set this to wayland to force calibre to use Wayland and xcb to force use of
X11.
SYSFS_PATH - Use if sysfs is mounted somewhere other than /sys
http_proxy, https_proxy - used on Linux to specify an HTTP(S) proxy
See How to set environment variables in Windows
111
. If you are on macOS you can set environment variables by creating
the ~/Library/Preferences/calibre/macos-env.txt and putting the environment variables one per line
in it, for example:
CALIBRE_DEVELOP_FROM=$HOME/calibre-src/src
CALIBRE_NO_NATIVE_FILEDIALOGS=1
CALIBRE_CONFIG_DIRECTORY=~/.config/calibre
111
https://www.computerhope.com/issues/ch000549.htm
290 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
12.3 Tweaks
Tweaks are small changes that you can specify to control various aspects of calibre’s behavior. You can change them by
going to Preferences->Advanced->Tweaks. The default values for the tweaks are reproduced below
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
# License: GPLv3 Copyright: 2010, Kovid Goyal <kovid at kovidgoyal.net>
# Contains various tweaks that affect calibre behavior. Only edit this file if
# you know what you are doing. If you delete this file, it will be recreated from
# defaults.
#: Auto increment series index
# The algorithm used to assign a book added to an existing series a series number.
# New series numbers assigned using this tweak are always integer values, except
# if a constant non-integer is specified.
# Possible values are:
# next - First available integer larger than the largest existing number
# first_free - First available integer larger than 0
# next_free - First available integer larger than the smallest existing number
# last_free - First available integer smaller than the largest existing number.
,Return largest existing + 1 if no free number is found
# const - Assign the number 1 always
# no_change - Do not change the series index
# a number - Assign that number always. The number is not in quotes. Note that 0.0
,can be used here.
# Examples:
# series_index_auto_increment = 'next'
# series_index_auto_increment = 'next_free'
# series_index_auto_increment = 16.5
#
# Set the use_series_auto_increment_tweak_when_importing tweak to True to
# use the above values when importing/adding books. If this tweak is set to
# False (the default) then the series number will be set to 1 if it is not
# explicitly set during the import. If set to True, then the
# series index will be set according to the series_index_auto_increment setting.
# Note that the use_series_auto_increment_tweak_when_importing tweak is used
# only when a value is not provided during import. If the importing regular
# expression produces a value for series_index, or if you are reading metadata
# from books and the import plugin produces a value, then that value will
# be used irrespective of the setting of the tweak.
series_index_auto_increment = 'next'
use_series_auto_increment_tweak_when_importing = False
#: Add separator after completing an author name
# Set this if the completion separator should be appended to the end of the
# completed text to automatically begin a new completion operation for authors.
# It can be either True or False
authors_completer_append_separator = False
#: Author sort name algorithm
# The algorithm used to copy author to author_sort.
# Possible values are:
# invert: use "fn ln" -> "ln, fn"
# copy : copy author to author_sort without modification
(continues on next page)
12.3. Tweaks 291
calibre User Manual, Release 7.19.0
(continued from previous page)
# comma : use 'copy' if there is a ',' in the name, otherwise use 'invert'
# nocomma : "fn ln" -> "ln fn" (without the comma)
# When this tweak is changed, the author_sort values stored with each author
# must be recomputed by right-clicking on an author in the left-hand tags
# panel, selecting 'Manage authors', and pressing
# 'Recalculate all author sort values'.
#
# The author_name_suffixes are words that are ignored when they occur at the
# end of an author name. The case of the suffix is ignored and trailing
# periods are automatically handled.
#
# The same is true for author_name_prefixes.
#
# The author_name_copywords are a set of words which, if they occur in an
# author name, cause the automatically generated author sort string to be
# identical to the author's name. This means that the sort for a string like
# "Acme Inc." will be "Acme Inc." instead of "Inc., Acme".
#
# If author_use_surname_prefixes is enabled, any of the words in
# author_surname_prefixes will be treated as a prefix to the surname, if they
# occur before the surname. So for example, "John von Neumann" would be sorted
# as "von Neumann, John" and not "Neumann, John von".
author_sort_copy_method = 'comma'
author_name_suffixes = ('Jr', 'Sr', 'Inc', 'Ph.D', 'Phd',
'MD', 'M.D', 'I', 'II', 'III', 'IV',
'Junior', 'Senior')
author_name_prefixes = ('Mr', 'Mrs', 'Ms', 'Dr', 'Prof')
author_name_copywords = (
'Agency', 'Corporation', 'Company', 'Co.', 'Council',
'Committee', 'Inc.', 'Institute', 'National', 'Society', 'Club', 'Team',
'Software', 'Games', 'Entertainment', 'Media', 'Studios',
)
author_use_surname_prefixes = False
author_surname_prefixes = ('da', 'de', 'di', 'la', 'le', 'van', 'von')
#: Splitting multiple author names
# By default, calibre splits a string containing multiple author names on
# ampersands and the words "and" and "with". You can customize the splitting
# by changing the regular expression below. Strings are split on whatever the
# specified regular expression matches, in addition to ampersands.
# Default: r'(?i),?\s+(and|with)\s+'
authors_split_regex = r'(?i),?\s+(and|with)\s+'
#: Use author sort in Tag browser
# Set which author field to display in the Tag browser (the list of authors,
# series, publishers etc on the left hand side). The choices are author and
# author_sort. This tweak affects only what is displayed under the authors
# category in the Tag browser and Content server. Please note that if you set this
# to author_sort, it is very possible to see duplicate names in the list because
# although it is guaranteed that author names are unique, there is no such
# guarantee for author_sort values. Showing duplicates won't break anything, but
# it could lead to some confusion. When using 'author_sort', the tooltip will
# show the author's name.
# Examples:
# categories_use_field_for_author_name = 'author'
# categories_use_field_for_author_name = 'author_sort'
categories_use_field_for_author_name = 'author'
(continues on next page)
292 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
(continued from previous page)
#: Control partitioning of Tag browser
# When partitioning the Tag browser, the format of the subcategory label is
# controlled by a template: categories_collapsed_name_template if sorting by
# name, categories_collapsed_rating_template if sorting by average rating, and
# categories_collapsed_popularity_template if sorting by popularity. There are
# two variables available to the template: first and last. The variable 'first'
# is the initial item in the subcategory, and the variable 'last' is the final
# item in the subcategory. Both variables are 'objects'; they each have multiple
# values that are obtained by using a suffix. For example, first.name for an
# author category will be the name of the author. The sub-values available are:
# name: the printable name of the item
# count: the number of books that references this item
# avg_rating: the average rating of all the books referencing this item
# sort: the sort value. For authors, this is the author_sort for that author
# category: the category (e.g., authors, series) that the item is in.
# Note that the "r'" in front of the { is necessary if there are backslashes
# (\ characters) in the template. It doesn't hurt anything to leave it there
# even if there aren't any backslashes.
categories_collapsed_name_template = r'{first.sort:shorten(4,,0)} - {last.
,sort:shorten(4,,0)}'
categories_collapsed_rating_template = r'{first.avg_rating:4.2f:ifempty(0)} - {last.
,avg_rating:4.2f:ifempty(0)}'
categories_collapsed_popularity_template = r'{first.count:d} - {last.count:d}'
#: Specify columns to sort the booklist by on startup
# Provide a set of columns to be sorted on when calibre starts.
# The argument is None if saved sort history is to be used
# otherwise it is a list of column,order pairs. Column is the
# lookup/search name, found using the tooltip for the column
# Order is 0 for ascending, 1 for descending.
# For example, set it to [('authors',0),('title',0)] to sort by
# title within authors.
sort_columns_at_startup = None
#: Control how dates are displayed
# Format to be used for publication date and the timestamp (date).
# A string controlling how the publication date is displayed in the GUI
# 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-12)
# MM the month as number with a leading zero (01-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-99)
# yyyy the year as four digit number
# h the hours without a leading 0 (0 to 11 or 0 to 23, depending on am/pm) '
# hh the hours with a leading 0 (00 to 11 or 00 to 23, depending on am/pm) '
# m the minutes without a leading 0 (0 to 59) '
# mm the minutes with a leading 0 (00 to 59) '
# s the seconds without a leading 0 (0 to 59) '
# ss the seconds with a leading 0 (00 to 59) '
# ap use a 12-hour clock instead of a 24-hour clock, with "ap" replaced by the
,localized string for am or pm
# AP use a 12-hour clock instead of a 24-hour clock, with "AP" replaced by the
(continues on next page)
12.3. Tweaks 293
calibre User Manual, Release 7.19.0
(continued from previous page)
,localized string for AM or PM
# iso the date with time and timezone. Must be the only format present
# For example, given the date of 9 Jan 2010, the following formats show
# MMM yyyy ==> Jan 2010 yyyy ==> 2010 dd MMM yyyy ==> 09 Jan 2010
# MM/yyyy ==> 01/2010 d/M/yy ==> 9/1/10 yy ==> 10
#
# publication default if not set: MMM yyyy
# timestamp default if not set: dd MMM yyyy
# last_modified_display_format if not set: dd MMM yyyy
gui_pubdate_display_format = 'MMM yyyy'
gui_timestamp_display_format = 'dd MMM yyyy'
gui_last_modified_display_format = 'dd MMM yyyy'
#: Control sorting of titles and series in the library display
# Control title and series sorting in the library view. If set to
# 'library_order', the title sort field will be used instead of the title.
# Unless you have manually edited the title sort field, leading articles such as
# The and A will be ignored. If set to 'strictly_alphabetic', the titles will be
# sorted as-is (sort by title instead of title sort). For example, with
# library_order, The Client will sort under 'C'. With strictly_alphabetic, the
# book will sort under 'T'.
# This flag affects calibre's library display. It has no effect on devices. In
# addition, titles for books added before changing the flag will retain their
# order until the title is edited. Editing a title and hitting Enter
# without changing anything is sufficient to change the sort. Or you can use
# the 'Update title sort' action in the Bulk metadata edit dialog to update
# it for many books at once.
title_series_sorting = 'library_order'
#: Control formatting of title and series when used in templates
# Control how title and series names are formatted when saving to disk/sending
# to device. The behavior depends on the field being processed. If processing
# title, then if this tweak is set to 'library_order', the title will be
# replaced with title_sort. If it is set to 'strictly_alphabetic', then the
# title will not be changed. If processing series, then if set to
# 'library_order', articles such as 'The' and 'An' will be moved to the end. If
# set to 'strictly_alphabetic', the series will be sent without change.
# For example, if the tweak is set to library_order, "The Lord of the Rings"
# will become "Lord of the Rings, The". If the tweak is set to
# strictly_alphabetic, it would remain "The Lord of the Rings". Note that the
# formatter function raw_field will return the base value for title and
# series regardless of the setting of this tweak.
save_template_title_series_sorting = 'library_order'
#: Set the list of words considered to be "articles" for sort strings
# Set the list of words that are to be considered 'articles' when computing the
# title sort strings. The articles differ by language. By default, calibre uses
# a combination of articles from English and whatever language the calibre user
# interface is set to. In addition, in some contexts where the book language is
# available, the language of the book is used. You can change the list of
# articles for a given language or add a new language by editing
# per_language_title_sort_articles. To tell calibre to use a language other
# than the user interface language, set, default_language_for_title_sort. For
# example, to use German, set it to 'deu'. A value of None means the user
# interface language is used. The setting title_sort_articles is ignored
# (present only for legacy reasons).
per_language_title_sort_articles = {
(continues on next page)
294 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
(continued from previous page)
# English
'eng' : (r'A\s+', r'The\s+', r'An\s+'),
# Esperanto
'epo': (r'La\s+', r"L'", 'L´'),
# Spanish
'spa' : (r'El\s+', r'La\s+', r'Lo\s+', r'Los\s+', r'Las\s+', r'Un\s+',
r'Una\s+', r'Unos\s+', r'Unas\s+'),
# French
'fra' : (r'Le\s+', r'La\s+', r"L'", u'L´', u'L’', r'Les\s+', r'Un\s+', r'Une\
,s+',
r'Des\s+', r'De\s+La\s+', r'De\s+', r"D'", r'D´', r'D’'),
# Polish
'pol': (),
# Italian
'ita': ('Lo\\s+', 'Il\\s+', "L'", 'L´', 'La\\s+', 'Gli\\s+',
'I\\s+', 'Le\\s+', 'Uno\\s+', 'Un\\s+', 'Una\\s+', "Un'",
'Un´', 'Dei\\s+', 'Degli\\s+', 'Delle\\s+', 'Del\\s+',
'Della\\s+', 'Dello\\s+', "Dell'", 'Dell´'),
# Portuguese
'por' : (r'A\s+', r'O\s+', r'Os\s+', r'As\s+', r'Um\s+', r'Uns\s+',
r'Uma\s+', r'Umas\s+', ),
# Romanian
'ron' : (r'Un\s+', r'O\s+', r'Nişte\s+', ),
# German
'deu' : (r'Der\s+', r'Die\s+', r'Das\s+', r'Den\s+', r'Ein\s+',
r'Eine\s+', r'Einen\s+', r'Dem\s+', r'Des\s+', r'Einem\s+',
r'Eines\s+'),
# Dutch
'nld' : (r'De\s+', r'Het\s+', r'Een\s+', r"'n\s+", r"'s\s+", r'Ene\s+',
r'Ener\s+', r'Enes\s+', r'Den\s+', r'Der\s+', r'Des\s+',
r"'t\s+"),
# Swedish
'swe' : (r'En\s+', r'Ett\s+', r'Det\s+', r'Den\s+', r'De\s+', ),
# Turkish
'tur' : (r'Bir\s+', ),
# Afrikaans
'afr' : (r"'n\s+", r'Die\s+', ),
# Greek
'ell' : (r'O\s+', r'I\s+', r'To\s+', r'Ta\s+', r'Tus\s+', r'Tis\s+',
r"'Enas\s+", r"'Mia\s+", r"'Ena\s+", r"'Enan\s+", ),
# Hungarian
'hun' : (r'A\s+', r'Az\s+', r'Egy\s+',),
}
default_language_for_title_sort = None
title_sort_articles=r'^(A|The|An)\s+'
#: Specify a folder calibre should connect to at startup
# Specify a folder that calibre should connect to at startup using
# connect_to_folder. This must be a full path to the folder. If the folder does
# not exist when calibre starts, it is ignored.
# Example for Windows:
# auto_connect_to_folder = 'C:/Users/someone/Desktop/testlib'
# Example for other operating systems:
# auto_connect_to_folder = '/home/dropbox/My Dropbox/someone/library'
auto_connect_to_folder = ''
#: Specify renaming rules for SONY collections
(continues on next page)
12.3. Tweaks 295
calibre User Manual, Release 7.19.0
(continued from previous page)
# Specify renaming rules for SONY collections. This tweak is only applicable if
# metadata management is set to automatic. Collections on SONYs are named
# depending upon whether the field is standard or custom. A collection derived
# from a standard field is named for the value in that field.
#
# For example, if the standard 'series' column contains the value 'Darkover', then the
# collection name is 'Darkover'. A collection derived from a custom field will
# have the name of the field added to the value. For example, if a custom series
# column named 'My Series' contains the name 'Darkover', then the collection
# will by default be named 'Darkover (My Series)'. For purposes of this
# documentation, 'Darkover' is called the value and 'My Series' is called the
# category. If two books have fields that generate the same collection name,
# then both books will be in that collection.
#
# This set of tweaks lets you specify for a standard or custom field how
# the collections are to be named. You can use it to add a description to a
# standard field, for example 'Foo (Tag)' instead of the 'Foo'. You can also use
# it to force multiple fields to end up in the same collection.
#
# For example, you could force the values in 'series', '#my_series_1', and
# '#my_series_2' to appear in collections named 'some_value (Series)', thereby
# merging all of the fields into one set of collections.
#
# There are two related tweaks. The first determines the category name to use
# for a metadata field. The second is a template, used to determines how the
# value and category are combined to create the collection name.
# The syntax of the first tweak, sony_collection_renaming_rules, is:
# {'field_lookup_name':'category_name_to_use', 'lookup_name':'name', ...}
#
# The second tweak, sony_collection_name_template, is a template. It uses the
# same template language as plugboards and save templates. This tweak controls
# how the value and category are combined together to make the collection name.
# The only two fields available are {category} and {value}. The {value} field is
# never empty. The {category} field can be empty. The default is to put the
# value first, then the category enclosed in parentheses, it isn't empty:
# '{value} {category:|(|)}'
#
# Examples: The first three examples assume that the second tweak
# has not been changed.
#
# 1) I want three series columns to be merged into one set of collections. The
# column lookup names are 'series', '#series_1' and '#series_2'. I want nothing
# in the parenthesis. The value to use in the tweak value would be:
# sony_collection_renaming_rules={'series':'', '#series_1':'', '#series_2':''}
#
# 2) I want the word '(Series)' to appear on collections made from series, and
# the word '(Tag)' to appear on collections made from tags. Use:
# sony_collection_renaming_rules={'series':'Series', 'tags':'Tag'}
#
# 3) I want 'series' and '#myseries' to be merged, and for the collection name
# to have '(Series)' appended. The renaming rule is:
# sony_collection_renaming_rules={'series':'Series', '#myseries':'Series'}
#
# 4) Same as example 2, but instead of having the category name in parentheses
# and appended to the value, I want it prepended and separated by a colon, such
# as in Series: Darkover. I must change the template used to format the category name
#
(continues on next page)
296 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
(continued from previous page)
# The resulting two tweaks are:
# sony_collection_renaming_rules={'series':'Series', 'tags':'Tag'}
# sony_collection_name_template='{category:||: }{value}'
sony_collection_renaming_rules={}
sony_collection_name_template='{value}{category:| (|)}'
#: Specify how SONY collections are sorted
# Specify how SONY collections are sorted. This tweak is only applicable if
# metadata management is set to automatic. You can indicate which metadata is to
# be used to sort on a collection-by-collection basis. The format of the tweak
# is a list of metadata fields from which collections are made, followed by the
# name of the metadata field containing the sort value.
# Example: The following indicates that collections built from pubdate and tags
# are to be sorted by the value in the custom column '#mydate', that collections
# built from 'series' are to be sorted by 'series_index', and that all other
# collections are to be sorted by title. If a collection metadata field is not
# named, then if it is a series- based collection it is sorted by series order,
# otherwise it is sorted by title order.
# [(['pubdate', 'tags'],'#mydate'), (['series'],'series_index'), (['*'], 'title')]
# Note that the bracketing and parentheses are required. The syntax is
# [ ( [list of fields], sort field ) , ( [ list of fields ] , sort field ) ]
# Default: empty (no rules), so no collection attributes are named.
sony_collection_sorting_rules = []
#: Control how tags are applied when copying books to another library
# Set this to True to ensure that tags in 'Tags to add when adding
# a book' are added when copying books to another library
add_new_book_tags_when_importing_books = False
#: Set the maximum number of sort 'levels'
# Set the maximum number of sort 'levels' that calibre will use to resort the
# library after certain operations such as searches or device insertion. Each
# sort level adds a performance penalty. If the database is large (thousands of
# books) the penalty might be noticeable. If you are not concerned about multi-
# level sorts, and if you are seeing a slowdown, reduce the value of this tweak.
maximum_resort_levels = 5
#: Choose whether dates are sorted using visible fields
# Date values contain both a date and a time. When sorted, all the fields are
# used, regardless of what is displayed. Set this tweak to True to use only
# the fields that are being displayed.
sort_dates_using_visible_fields = False
#: Fuzz value for trimming covers
# The value used for the fuzz distance when trimming a cover.
# Colors within this distance are considered equal.
# The distance is in absolute intensity units.
cover_trim_fuzz_value = 10
#: Control behavior of the book list
# You can control the behavior of double clicks and pressing Enter on the books
# list. Choices: open_viewer, do_nothing, show_book_details,
# show_locked_book_details, edit_cell, edit_metadata. Selecting anything other
# than open_viewer, show_book_details, or show_locked_book_details has the side
# effect of disabling editing a field using a single click.
# Default: open_viewer.
# Example: doubleclick_on_library_view = 'do_nothing'
(continues on next page)
12.3. Tweaks 297
calibre User Manual, Release 7.19.0
(continued from previous page)
# You can also control whether the book list scrolls per item or
# per pixel. Default is per item.
doubleclick_on_library_view = 'open_viewer'
enter_key_behavior = 'do_nothing'
horizontal_scrolling_per_column = False
vertical_scrolling_per_row = False
#: Language to use when sorting
# Setting this tweak will force sorting to use the
# collating order for the specified language. This might be useful if you run
# calibre in English but want sorting to work in the language where you live.
# Set the tweak to the desired ISO 639-1 language code, in lower case.
# You can find the list of supported locales at
# https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
# Default: locale_for_sorting = '' -- use the language calibre displays in
# Example: locale_for_sorting = 'fr' -- sort using French rules.
# Example: locale_for_sorting = 'nb' -- sort using Norwegian rules.
locale_for_sorting = ''
#: The number of seconds to wait before sending emails
# The number of seconds to wait before sending emails when using a
# public email server like GMX/Hotmail/Gmail. Default is: 5 minutes
# Setting it to lower may cause the server's SPAM controls to kick in,
# making email sending fail. Changes will take effect only after a restart of
# calibre. You can also change the list of hosts that calibre considers
# to be public relays here. Any relay host ending with one of the suffixes
# in the list below will be considered a public email server.
public_smtp_relay_delay = 301
public_smtp_relay_host_suffixes = ['gmail.com', 'live.com', 'gmx.com', 'outlook.com']
#: The maximum width and height for covers saved in the calibre library
# All covers in the calibre library will be resized, preserving aspect ratio,
# to fit within this size. This is to prevent slowdowns caused by extremely
# large covers
maximum_cover_size = (1650, 2200)
#: Where to send downloaded news
# When automatically sending downloaded news to a connected device, calibre
# will by default send it to the main memory. By changing this tweak, you can
# control where it is sent. Valid values are "main", "carda", "cardb". Note
# that if there isn't enough free space available on the location you choose,
# the files will be sent to the location with the most free space.
send_news_to_device_location = "main"
#: Unified toolbar on macOS
# If you enable this option and restart calibre, the toolbar will be 'unified'
# with the titlebar as is normal for macOS applications. However, doing this has
# various bugs, for instance the minimum width of the toolbar becomes twice
# what it should be and it causes other random bugs on some systems, so turn it
# on at your own risk!
unified_title_toolbar_on_osx = False
#: Save original file when converting/polishing from same format to same format
# When calibre does a conversion from the same format to the same format, for
# example, from EPUB to EPUB, the original file is saved, so that in case the
# conversion is poor, you can tweak the settings and run it again. By setting
# this to False you can prevent calibre from saving the original file.
(continues on next page)
298 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
(continued from previous page)
# Similarly, by setting save_original_format_when_polishing to False you can
# prevent calibre from saving the original file when polishing.
save_original_format = True
save_original_format_when_polishing = True
#: Number of recently viewed books to show
# Right-clicking the "View" button shows a list of recently viewed books. Control
# how many should be shown, here.
gui_view_history_size = 15
#: Change the font size of the Book details panel in the interface
# Change the font size at which book details are rendered in the side panel and
# comments are rendered in the metadata edit dialog. Set it to a positive or
# negative number to increase or decrease the font size.
change_book_details_font_size_by = 0
#: What format to default to when using the "Unpack book" feature
# The "Unpack book" feature of calibre allows direct editing of a book format.
# If multiple formats are available, calibre will offer you a choice
# of formats, defaulting to your preferred output format if it is available.
# Set this tweak to a specific value of 'EPUB' or 'AZW3' to always default
# to that format rather than your output format preference.
# Set to a value of 'remember' to use whichever format you chose last time you
# used the "Unpack book" feature.
# Examples:
# default_tweak_format = None (Use output format)
# default_tweak_format = 'EPUB'
# default_tweak_format = 'remember'
default_tweak_format = None
#: Do not preselect a completion when editing authors/tags/series/etc.
# This means that you can make changes and press Enter and your changes will
# not be overwritten by a matching completion. However, if you wish to use the
# completions you will now have to press Tab to select one before pressing
# Enter. Which technique you prefer will depend on the state of metadata in
# your library and your personal editing style.
#
# If preselect_first_completion is False and you want Tab to accept what you
# typed instead of the first completion then set tab_accepts_uncompleted_text
# to True. If you do this then to select from the completions you must press
# the Down or Up arrow keys. The tweak tab_accepts_uncompleted_text is ignored
# if preselect_first_completion is True
preselect_first_completion = False
tab_accepts_uncompleted_text = False
#: Completion mode when editing authors/tags/series/etc.
# By default, when completing items, calibre will show you all the candidates
# that start with the text you have already typed. You can instead have it show
# all candidates that contain the text you have already typed. To do this, set
# completion_mode to 'contains'. For example, if you type asi it will match both
# Asimov and Quasimodo, whereas the default behavior would match only Asimov.
completion_mode = 'prefix'
#: Sort the list of libraries alphabetically
# The list of libraries in the Copy to library and Quick switch menus are
# normally sorted by most used. However, if there are more than a certain
# number of such libraries, the sorting becomes alphabetic. You can set that
(continues on next page)
12.3. Tweaks 299
calibre User Manual, Release 7.19.0
(continued from previous page)
# number here. The default is ten libraries.
many_libraries = 10
#: Choose available output formats for conversion
# Restrict the list of available output formats in the conversion dialogs.
# For example, if you only want to convert to EPUB and AZW3, change this to
# restrict_output_formats = ['EPUB', 'AZW3']. The default value of None causes
# all available output formats to be present.
restrict_output_formats = None
#: Set the thumbnail image quality used by the Content server
# The quality of a thumbnail is largely controlled by the compression quality
# used when creating it. Set this to a larger number to improve the quality.
# Note that the thumbnails get much larger with larger compression quality
# numbers.
# The value can be between 50 and 99
content_server_thumbnail_compression_quality = 75
#: Image file types to treat as e-books when dropping onto the "Book details" panel
# Normally, if you drop any image file in a format known to calibre onto the
# "Book details" panel, it will be used to set the cover. If you want to store
# some image types as e-books instead, you can set this tweak.
# Examples:
# cover_drop_exclude = {'tiff', 'webp'}
cover_drop_exclude = ()
#: Exclude fields when copy/pasting metadata
# You can ask calibre to not paste some metadata fields when using the
# Edit metadata->Copy metadata/Paste metadata actions. For example,
# exclude_fields_on_paste = ['cover', 'timestamp', '#mycolumn']
# to prevent pasting of the cover, Date and custom column, mycolumn.
# You can also add a shortcut in Preferences->Shortcuts->Edit metadata
# to paste metadata ignoring this tweak.
exclude_fields_on_paste = []
#: Skip internet connected check
# Skip checking whether the internet is available before downloading news.
# Useful if for some reason your operating systems network checking
# facilities are not reliable (for example NetworkManager on Linux).
skip_network_check = False
#: Tab stop width in the template editor
# Sets the width of the tab stop in the template editor in "average characters".
# For example, a value of 1 results in a space with the width of one average
,character.
template_editor_tab_stop_width = 4
#: Value for undefined numbers when sorting
# Sets the value to use for undefined numbers when sorting.
# For example, the value -10 sorts undefined numbers as if they were set to -10.
# Use 'maximum' for the largest possible number. Use 'minimum' for the smallest
# possible number. Quotes are optional if entering a number.
# Examples:
# value_for_undefined_numbers_when_sorting = -100
# value_for_undefined_numbers_when_sorting = '2'
# value_for_undefined_numbers_when_sorting = -0.01
# value_for_undefined_numbers_when_sorting = 'minimum'
(continues on next page)
300 Chapter 12. Customizing calibre
calibre User Manual, Release 7.19.0
(continued from previous page)
# value_for_undefined_numbers_when_sorting = 'maximum'
value_for_undefined_numbers_when_sorting = 0
#: Allow template database functions in composite columns
# If True then the template database functions book_values() and book_count()
# can be used in composite custom columns. Note: setting this tweak to True and
# using these functions in composites can be very slow.
# Default: False
allow_template_database_functions_in_composites = False
#: Change the programs that are run when opening files/URLs
# By default, calibre passes URLs to the operating system to open using
# whatever default programs are configured there. Here you can override
# that by specifying the program to use, per URL type. For local files,
# the type is "file" and for web links it is "http*". For example:
# openers_by_scheme = { "http*": "firefox %u" } will make calibre run Firefox
# for https://whatever URLs. %u is replaced by the URL to be opened. The scheme
# takes a glob pattern allowing a single entry to match multiple URL types.
openers_by_scheme = {}
#: Set the first day of the week for calendar popups
# It must be one of the values Default, Sunday, Monday, Tuesday, Wednesday,
# Thursday, Friday, or Saturday, all in English, spelled exactly as shown.
calendar_start_day_of_week = 'Default'
12.4 Overriding icons, templates, et cetera
® Note
calibre has direct support for icon themes, there are several icon themes available for calibre, that you can use by going
to Preferences → Interface → Look & Feel → Change icon theme. It is preferable to use icon themes over overriding
individual icons.
calibre allows you to override the static resources, like icons, JavaScript and templates for the metadata jacket, catalogs,
etc. with customized versions that you like. All static resources are stored in the resources sub-folder of the calibre
install location. On Windows, this is usually C:\Program Files\Calibre2\app\resources. On macOS,
/Applications/calibre.app/Contents/Resources/resources/. On Linux, if you are using the bi-
nary installer from the calibre website it will be /opt/calibre/resources. These paths can change depending on
where you choose to install calibre.
You should not change the les in this resources folder, as your changes will get overwritten the next time you update
calibre. Instead, go to Preferences → Advanced → Miscellaneous and click Open calibre conguration folder. In this
conguration folder, create a sub-folder called resources and place the les you want to override in it. Place the les in
the appropriate sub folders, for example place images in resources/images, etc. calibre will automatically use your
custom le in preference to the built-in one the next time it is started.
For example, if you wanted to change the icon for the Remove books action, you would rst look in the built-in resources
folder and see that the relevant le is resources/images/remove_books.png. Assuming you have an alternate
icon in PNG format called my_remove_books.png you would save it in the conguration folder as resources/
images/remove_books.png
. All the icons used by the calibre user interface are in
resources/images
and
its sub-folders. Placing an override le here will have even higher priority than a custom icon theme.
12.4. Overriding icons, templates, et cetera 301
calibre User Manual, Release 7.19.0
12.5 Creating your own icon theme for calibre
If you have created a beautiful set of icons and wish to share them with other calibre users via calibre’s builtin icon
theme support, you can easily package up your icons into a theme. To do so, go to Preferences → Miscellaneous → Create
icon theme, select the folder where you have put your icons. Then ll up the theme metadata and click OK. This will
result in a ZIP le containing the theme icons. You can upload that to the calibre forum at Mobileread
112
and then I
will make your theme available via calibre’s builtin icon theme system. By default, the icon theme you just created will
also be installed as the current theme in calibre. If you are testing your theme, remember to remove the images from the
resources/images folder so that the icons from the theme are used.
As of calibre 6, you can have custom icons for light and dark mode. Simply create two versions of the
icon and name the les with the sux -for-dark-theme and -for-light-theme. For example,
modified-for-dark-theme.png and modified-for-light-theme.png. Then calibre will automati-
cally use the appropriate icon based on the current theme.
12.6 Customizing calibre with plugins
calibre has a very modular design. Almost all functionality in calibre comes in the form of plugins. Plugins are used
for conversion, for downloading news (though these are called recipes), for various components of the user interface, to
connect to dierent devices, to process les when adding them to calibre and so on. You can get a complete list of all the
built-in plugins in calibre by going to Preferences → Advanced → Plugins.
You can write your own plugins to customize and extend the behavior of calibre. The plugin architecture in calibre is very
simple, see the tutorial Writing your own plugins to extend calibre’s functionality (page 226).
Once you have written a plugin, you can upload that to the calibre plugins forum at Mobileread
113
and it will be made
available via calibre’s builtin plugin updater.
112
https://www.mobileread.com/forums/forumdisplay.php?f=166
113
https://www.mobileread.com/forums/forumdisplay.php?f=237
302 Chapter 12. Customizing calibre
CHAPTER
THIRTEEN
COMMAND LINE INTERFACE
® Note
On macOS, the command line tools are inside the calibre bundle, for example, if you installed calibre in /
Applications the command line tools are in /Applications/calibre.app/Contents/MacOS/.
So, for example, to run ebook-convert you would use: /Applications/calibre.app/Contents/
MacOS/ebook-convert.
13.1 Documented commands
13.1.1 calibre
calibre [options] [path_to_ebook or calibre url ...]
Launch the main calibre Graphical User Interface and optionally add the e-book at path_to_ebook to the database.
You can also specify calibre URLs to perform various dierent actions, than just adding books. For example:
calibre://view-book/test_library/1842/epub
Will open the book with id 1842 in the EPUB format from the library “test_library” in the calibre E-book viewer.
Library names are the folder names of the libraries with spaces replaced by underscores. A full description of the various
URL based actions is in the User Manual.
Whenever you pass arguments to calibre that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
[options]
--detach
Detach from the controlling terminal, if any (Linux only)
--help, -h
show this help message and exit
--ignore-plugins
Ignore custom plugins, useful if you installed a plugin that is preventing calibre from starting
303
calibre User Manual, Release 7.19.0
--no-update-check
Do not check for updates
--shutdown-running-calibre, -s
Cause a running calibre instance, if any, to be shutdown. Note that if there are running jobs, they will be silently
aborted, so use with care.
--start-in-tray
Start minimized to system tray.
--verbose, -v
Ignored, do not use. Present only for legacy reasons
--version
show program's version number and exit
--with-library
Use the library located at the specied path.
13.1.2 calibre-customize
calibre-customize options
Customize calibre by loading external plugins.
Whenever you pass arguments to calibre-customize that have spaces in them, enclose the arguments in quotation
marks. For example: “/some path/with spaces”
[options]
--add-plugin, -a
Add a plugin by specifying the path to the ZIP le containing it.
--build-plugin, -b
For plugin developers: Path to the folder where you are developing the plugin. This command will automatically
zip up the plugin and update it in calibre.
--customize-plugin
Customize plugin. Specify name of plugin and customization string separated by a comma. The customization
string is the same as you would enter when customizing the plugin in the main calibre GUI.
--disable-plugin
Disable the named plugin
--enable-plugin
Enable the named plugin
--help, -h
show this help message and exit
--list-plugins, -l
List all installed plugins
--remove-plugin, -r
Remove a custom plugin by name. Has no eect on builtin plugins
304 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--version
show program's version number and exit
13.1.3 calibre-debug
calibre-debug [options]
Various command line interfaces useful for debugging calibre. With no options, this command starts an embedded Python
interpreter. You can also run the main calibre GUI, the calibre E-book viewer and the calibre editor in debug mode.
It also contains interfaces to various bits of calibre that do not have dedicated command line tools, such as font subsetting,
the E-book di tool and so on.
You can also use calibre-debug to run standalone scripts. To do that use it like this:
calibre-debug -e myscript.py -- --option1 --option2 le1 le2
Everything after the -- is passed to the script. You can also use calibre-debug as a shebang in scripts, like this:
#!/usr/bin/env -S calibre-debug -e --
Whenever you pass arguments to calibre-debug that have spaces in them, enclose the arguments in quotation marks.
For example: “/some path/with spaces”
[options]
--add-simple-plugin
Add a simple plugin (i.e. a plugin that consists of only a .py le), by specifying the path to the py le containing
the plugin code.
--command, -c
Run Python code.
--debug-device-driver, -d
Debug device detection
--default-programs
(Un)register calibre from Windows Default Programs. --default-programs (page 305) = (regis-
ter|unregister)
--diff
Run the calibre di tool. For example: calibre-debug --diff (page 305) le1 le2
--edit-book
Launch the calibre "Edit book" tool in debug mode.
--exec-file, -e
Run the Python code in le.
--explode-book, -x
Explode the book into the specied folder. Usage: -x le.epub output_dir Exports the book as a collection of
HTML les and metadata, which you can edit using standard HTML editing tools. Works with EPUB, AZW3,
HTMLZ and DOCX les.
13.1. Documented commands 305
calibre User Manual, Release 7.19.0
--export-all-calibre-data
Export all calibre data (books/settings/plugins). Normally, you will be asked for the export folder and the li-
braries to export. You can also specify them as command line arguments to skip the questions. Use ab-
solute paths for the export folder and libraries. The special keyword "all" can be used to export all li-
braries. Examples: calibre-debug --export-all-calibre-data (page 305) # for interactive use calibre-
debug --export-all-calibre-data (page 305) /path/to/empty/export/folder /path/to/library/folder1
/path/to/library2 calibre-debug --export-all-calibre-data (page 305) /export/folder all # export all
known libraries
--fix-multiprocessing
For internal use
--gui, -g
Run the GUI with debugging enabled. Debug output is printed to stdout and stderr.
--gui-debug
Run the GUI with a debug console, logging to the specied path. For internal use only, use the -g option to run the
GUI in debug mode
--help, -h
show this help message and exit
--implode-book, -i
Implode a previously exploded book. Usage: -i output_dir le.epub Imports the book from the les in output_dir
which must have been created by a previous call to --explode-book (page 305). Be sure to specify the same
le type as was used when exploding.
--import-calibre-data
Import previously exported calibre data
--inspect-mobi, -m
Inspect the MOBI le(s) at the specied path(s)
--paths
Output the paths necessary to setup the calibre environment
--run-plugin, -r
Run a plugin that provides a command line interface. For example: calibre-debug -r "Plugin name" -- le1
--option1 Everything after the -- will be passed to the plugin as arguments.
--run-test, -t
Run the named test(s). Use the special value "all" to run all tests. If the test name starts with a period it is assumed
to be a module name. If the test name starts with @ it is assumed to be a category name.
--run-without-debug
Don't run with the DEBUG ag set
--shutdown-running-calibre, -s
Cause a running calibre instance, if any, to be shutdown. Note that if there are running jobs, they will be silently
aborted, so use with care.
--subset-font, -f
Subset the specied font. Use -- after this option to pass option to the font subsetting program.
--test-build
Test binary modules in build
306 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--version
show program's version number and exit
--viewer, -w
Run the E-book viewer in debug mode
13.1.4 calibre-server
calibre-server [options] [path to library folder...]
Start the calibre Content server. The calibre Content server exposes your calibre libraries over the internet. You can
specify the path to the library folders as arguments to calibre-server. If you do not specify any paths, all the
libraries that the main calibre program knows about will be used.
Whenever you pass arguments to calibre-server that have spaces in them, enclose the arguments in quotation
marks. For example: “/some path/with spaces”
[options]
--access-log
Path to the access log le. This log contains information about clients connecting to the server and making requests.
By default no access logging is done.
--ajax-timeout
Time (in seconds) to wait for a response from the server when making queries.
--auth-mode
Choose the type of authentication used. Set the HTTP authentication mode used by the server. Set to "basic" if
you are putting this server behind an SSL proxy. Otherwise, leave it as "auto", which will use "basic" if SSL is
congured otherwise it will use "digest".
--auto-reload
Automatically reload server when source code changes. Useful for development. You should also specify a small
value for the shutdown timeout.
--ban-after
Number of login failures for ban. The number of login failures after which an IP address is banned
--ban-for
Ban IP addresses that have repeated login failures. Temporarily bans access for IP addresses that have repeated
login failures for the specied number of minutes. Useful to prevent attempts at guessing passwords. If set to zero,
no banning is done.
--book-list-mode
Choose the default book list mode. Set the default book list mode that will be used for new users. Individual users
can override the default in their own settings. The default is to use a cover grid.
--compress-min-size
Minimum size for which responses use data compression (in bytes).
--custom-list-template
Path to a JSON le containing a template for the custom book list mode. The easiest way to create such a template
le is to go to Preferences-> Sharing over the net-> Book list template in calibre, create the template and export it.
13.1. Documented commands 307
calibre User Manual, Release 7.19.0
--daemonize
Run process in background as a daemon (Linux only).
--displayed-fields
Restrict displayed user-dened elds. Comma separated list of user-dened metadata elds that will be displayed
by the Content server in the /opds and /mobile views. If you specify this option, any elds not in this list will not
be displayed. For example: my_rating,my_tags
--enable-allow-socket-preallocation, --disable-allow-socket-preallocation
Socket pre-allocation, for example, with systemd socket activation. By default, this option is enabled.
--enable-auth, --disable-auth
Password based authentication to access the server. Normally, the server is unrestricted, allowing anyone to access
it. You can restrict access to predened users with this option. By default, this option is disabled.
--enable-fallback-to-detected-interface,
--disable-fallback-to-detected-interface
Fallback to auto-detected interface. If for some reason the server is unable to bind to the interface specied in
the listen_on option, then it will try to detect an interface that connects to the outside world and bind to that. By
default, this option is enabled.
--enable-local-write, --disable-local-write
Allow un-authenticated local connections to make changes. Normally, if you do not turn on authentication, the
server operates in read-only mode, so as to not allow anonymous users to make changes to your calibre libraries.
This option allows anybody connecting from the same computer as the server is running on to make changes. This
is useful if you want to run the server without authentication but still use calibredb to make changes to your calibre
libraries. Note that turning on this option means any program running on the computer can make changes to your
calibre libraries. By default, this option is disabled.
--enable-log-not-found, --disable-log-not-found
Log HTTP 404 (Not Found) requests. Normally, the server logs all HTTP requests for resources that are not found.
This can generate a lot of log spam, if your server is targeted by bots. Use this option to turn it o. By default, this
option is enabled.
--enable-use-bonjour, --disable-use-bonjour
Advertise OPDS feeds via BonJour. Advertise the OPDS feeds via the BonJour service, so that OPDS based
reading apps can detect and connect to the server automatically. By default, this option is enabled.
--enable-use-sendfile, --disable-use-sendfile
Zero copy le transfers for increased performance. This will use zero-copy in-kernel transfers when sending les
over the network, increasing performance. However, it can cause corrupted le transfers on some broken lesys-
tems. If you experience corrupted le transfers, turn it o. By default, this option is enabled.
--help, -h
show this help message and exit
--ignored-fields
Ignored user-dened metadata elds. Comma separated list of user-dened metadata elds that will not be displayed
by the Content server in the /opds and /mobile views. For example: my_rating,my_tags
--listen-on
The interface on which to listen for connections. The default is to listen on all available IPv6 and IPv4 interfaces.
You can change this to, for example, "127.0.0.1" to only listen for IPv4 connections from the local machine, or to
"0.0.0.0" to listen to all incoming IPv4 connections.
308 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--log
Path to log le for server log. This log contains server information and errors, not access logs. By default it is
written to stdout.
--manage-users
Manage the database of users allowed to connect to this server. You can use it in automated mode by adding a
–. See calibre-server --manage-users (page 309) -- help for details. See also the --userdb (page 310)
option.
--max-header-line-size
Max. size of single HTTP header (in KB).
--max-job-time
Maximum time for worker processes. Maximum amount of time worker processes are allowed to run (in minutes).
Set to zero for no limit.
--max-jobs
Maximum number of worker processes. Worker processes are launched as needed and used for large jobs such
as preparing a book for viewing, adding books, converting, etc. Normally, the max. number of such processes is
based on the number of CPU cores. You can control it by this setting.
--max-log-size
Max. log le size (in MB). The maximum size of log les, generated by the server. When the log becomes larger
than this size, it is automatically rotated. Set to zero to disable log rotation.
--max-opds-items
Maximum number of books in OPDS feeds. The maximum number of books that the server will return in a single
OPDS acquisition feed.
--max-opds-ungrouped-items
Maximum number of ungrouped items in OPDS feeds. Group items in categories such as author/tags by rst letter
when there are more than this number of items. Set to zero to disable.
--max-request-body-size
Max. allowed size for les uploaded to the server (in MB).
--num-per-page
Number of books to show in a single page. The number of books to show in a single page in the browser.
--pidfile
Write process PID to the specied le
--port
The port on which to listen for connections.
--search-the-net-urls
Path to a JSON le containing URLs for the "Search the internet" feature. The easiest way to create such a le is
to go to Preferences-> Sharing over the net->Search the internet in calibre, create the URLs and export them.
--shutdown-timeout
Total time in seconds to wait for clean shutdown.
--ssl-certfile
Path to the SSL certicate le.
--ssl-keyfile
Path to the SSL private key le.
13.1. Documented commands 309
calibre User Manual, Release 7.19.0
--timeout
Time (in seconds) after which an idle connection is closed.
--trusted-ips
Allow un-authenticated connections from specic IP addresses to make changes. Normally, if you do not turn on
authentication, the server operates in read-only mode, so as to not allow anonymous users to make changes to your
calibre libraries. This option allows anybody connecting from the specied IP addresses to make changes. Must
be a comma separated list of address or network specications. This is useful if you want to run the server without
authentication but still use calibredb to make changes to your calibre libraries. Note that turning on this option
means anyone connecting from the specied IP addresses can make changes to your calibre libraries.
--url-prefix
A prex to prepend to all URLs. Useful if you wish to run this server behind a reverse proxy. For example use,
/calibre as the URL prex.
--userdb
Path to the user database to use for authentication. The database is a SQLite le. To create it use
--manage-users (page 309). You can read more about managing users at: https://manual.calibre-ebook.
com/server.html#managing-user-accounts-from-the-command-line-only
--version
show program's version number and exit
--worker-count
Number of worker threads used to process requests.
13.1.5 calibre-smtp
calibre-smtp [options] [from to text]
Send mail using the SMTP protocol. calibre-smtp has two modes of operation. In the compose mode you specify
from to and text and these are used to build and send an email message. In the lter mode, calibre-smtp reads a
complete email message from STDIN and sends it.
text is the body of the email message. If text is not specied, a complete email message is read from STDIN. from is the
email address of the sender and to is the email address of the recipient. When a complete email is read from STDIN,
from and to are only used in the SMTP negotiation, the message headers are not modied.
Whenever you pass arguments to calibre-smtp that have spaces in them, enclose the arguments in quotation marks.
For example: “/some path/with spaces”
[options]
--fork, -f
Fork and deliver message in background. If you use this option, you should also use --outbox (page 310) to
handle delivery failures.
--help, -h
show this help message and exit
--localhost, -l
Host name of localhost. Used when connecting to SMTP server.
310 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--outbox, -o
Path to maildir folder to store failed email messages in.
--timeout, -t
Timeout for connection
--verbose, -v
Be more verbose
--version
show program's version number and exit
COMPOSE MAIL
Options to compose an email. Ignored if text is not specied
--attachment, -a
File to attach to the email
--subject, -s
Subject of the email
SMTP RELAY
Options to use an SMTP relay server to send mail. calibre will try to send the email directly unless –relay is specied.
--cafile
Path to a le of concatenated CA certicates in PEM format, used to verify the server certicate when using TLS.
By default, the system CA certicates are used.
--dont-verify-server-certificate
Do not verify the server certicate when connecting using TLS. This used to be the default behavior in calibre
versions before 3.27. If you are using a relay with a self-signed or otherwise invalid certicate, you can use this
option to restore the pre 3.27 behavior
--encryption-method, -e
Encryption method to use when connecting to relay. Choices are TLS, SSL and NONE. Default is TLS. WARN-
ING: Choosing NONE is highly insecure
--password, -p
Password for relay
--port
Port to connect to on relay server. Default is to use 465 if encryption method is SSL and 25 otherwise.
--relay, -r
An SMTP relay server to use to send mail.
--username, -u
Username for relay
13.1. Documented commands 311
calibre User Manual, Release 7.19.0
13.1.6 calibredb
calibredb command [options] [arguments]
calibredb is the command line interface to the calibre database. It has several sub-commands, documented below.
calibredb can be used to manipulate either a calibre database specied by path or a calibre Content server running
either on the local machine or over the internet. You can start a calibre Content server using either the calibre-server
program or in the main calibre program click Connect/share  →  Start Content server. Since calibredb can make
changes to your calibre libraries, you must setup authentication on the server rst. There are two ways to do that:
If you plan to connect only to a server running on the same computer, you can simply use the
--enable-local-write option of the Content server, to allow any program, including calibredb, running on
the local computer to make changes to your calibre data. When running the server from the main calibre program,
this option is in Preferences → Sharing over the net → Advanced.
If you want to enable access over the internet, then you should setup user accounts on the server and use
the --username (page 313) and --password (page 313) options to calibredb to give it access.
You can setup user authentication for calibre-server by using the --enable-auth option and using
--manage-users to create the user accounts. If you are running the server from the main calibre program, use
Preferences → Sharing over the net → Require username/password.
To connect to a running Content server, pass the URL of the server to the --with-library (page 313) option, see
the documentation of that option for details and examples.
Global Options (page 313)
list (page 313)
add (page 314)
Adding From Folders (page 315)
remove (page 316)
add_format (page 316)
remove_format (page 316)
show_metadata (page 316)
set_metadata (page 317)
export (page 317)
catalog (page 318)
Epub Options (page 319)
saved_searches (page 320)
add_custom_column (page 320)
custom_columns (page 321)
remove_custom_column (page 321)
set_custom (page 321)
restore_database (page 322)
check_library (page 322)
312 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
list_categories (page 322)
backup_metadata (page 323)
clone (page 323)
embed_metadata (page 323)
search (page 324)
fts_index (page 324)
fts_search (page 325)
Global Options
--help, -h
show this help message and exit
--library-path, --with-library
Path to the calibre library. Default is to use the path stored in the settings. You can also connect to a calibre Content
server to perform actions on remote libraries. To do so use a URL of the form: http://hostname:port/#library_id
for example, http://localhost:8080/#mylibrary. library_id is the library id of the library you want to connect to
on the Content server. You can use the special library_id value of - to get a list of library ids available on the
server. For details on how to setup access via a Content server, see https://manual.calibre-ebook.com/generated/
en/calibredb.html.
--password
Password for connecting to a calibre Content server. To read the password from standard input, use the special
value: <stdin>. To read the password from a le, use: <f:/path/to/le> (i.e. <f: followed by the full path to the le
and a trailing >). The angle brackets in the above are required, remember to escape them or use quotes for your
shell.
--timeout
The timeout, in seconds, when connecting to a calibre library over the network. The default is two minutes.
--username
Username for connecting to a calibre Content server
--version
show program's version number and exit
list
calibredb list [options]
List the books available in the calibre database.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--ascending
Sort results in ascending order
13.1. Documented commands 313
calibre User Manual, Release 7.19.0
--fields, -f
The elds to display when listing books in the database. Should be a comma separated list of elds. Available elds:
author_sort, authors, comments, cover, formats, identiers, isbn, languages, last_modied, pubdate, publisher,
rating, series, series_index, size, tags, template, timestamp, title, uuid Default: title,authors. The special eld "all"
can be used to select all elds. In addition to the builtin elds above, custom elds are also available as *eld_name,
for example, for a custom eld #rating, use the name: *rating
--for-machine
Generate output in JSON format, which is more suitable for machine parsing. Causes the line width and separator
options to be ignored.
--limit
The maximum number of results to display. Default: all
--line-width, -w
The maximum width of a single line in the output. Defaults to detecting screen size.
--prefix
The prex for all le paths. Default is the absolute path to the library folder.
--search, -s
Filter the results by the search query. For the format of the search query, please see the search related documentation
in the User Manual. Default is to do no ltering.
--separator
The string used to separate elds. Default is a space.
--sort-by
The eld by which to sort the results. You can specify multiple elds by separating them with commas. Avail-
able elds: author_sort, authors, comments, cover, formats, identiers, isbn, languages, last_modied, pubdate,
publisher, rating, series, series_index, size, tags, template, timestamp, title, uuid Default: id
--template
The template to run if "template" is in the eld list. Note that templates are ignored while connecting to a calibre
server. Default: None
--template_file, -t
Path to a le containing the template to run if "template" is in the eld list. Default: None
--template_heading
Heading for the template column. Default: template. This option is ignored if the option --for-machine
(page 314) is set
add
calibredb add [options] file1 file2 file3 ...
Add the specied les as books to the database. You can also specify folders, see the folder related options below.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--authors, -a
Set the authors of the added book(s)
314 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--automerge, -m
If books with similar titles and authors are found, merge the incoming formats (les) automatically into existing
book records. A value of "ignore" means duplicate formats are discarded. A value of "overwrite" means duplicate
formats in the library are overwritten with the newly added les. A value of "new_record" means duplicate formats
are placed into a new book record.
--cover, -c
Path to the cover to use for the added book
--duplicates, -d
Add books to database even if they already exist. Comparison is done based on book titles and authors. Note that
the --automerge (page 314) option takes precedence.
--empty, -e
Add an empty book (a book with no formats)
--identifier, -I
Set the identiers for this book, e.g. -I asin:XXX -I isbn:YYY
--isbn, -i
Set the ISBN of the added book(s)
--languages, -l
A comma separated list of languages (best to use ISO639 language codes, though some language names may also
be recognized)
--series, -s
Set the series of the added book(s)
--series-index, -S
Set the series number of the added book(s)
--tags, -T
Set the tags of the added book(s)
--title, -t
Set the title of the added book(s)
Adding From Folders
Options to control the adding of books from folders. By default only les that have extensions of known e-book le types
are added.
--add
A lename (glob) pattern, les matching this pattern will be added when scanning folders for les, even if they are
not of a known e-book le type. Can be specied multiple times for multiple patterns.
--ignore
A lename (glob) pattern, les matching this pattern will be ignored when scanning folders for les. Can be specied
multiple times for multiple patterns. For example: *.pdf will ignore all PDF les
--one-book-per-directory, -1
Assume that each folder has only a single logical book and that all les in it are dierent e-book formats of that
book
--recurse, -r
Process folders recursively
13.1. Documented commands 315
calibre User Manual, Release 7.19.0
remove
calibredb remove ids
Remove the books identied by ids from the database. ids should be a comma separated list of id numbers (you can get
id numbers by using the search command). For example, 23,34,57-85 (when specifying a range, the last number in the
range is not included).
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--permanent
Do not use the Recycle Bin
add_format
calibredb add_format [options] id ebook_file
Add the e-book in ebook_le to the available formats for the logical book identied by id. You can get id by using the
search command. If the format already exists, it is replaced, unless the do not replace option is specied.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--as-extra-data-file
Add the le as an extra data le to the book, not an ebook format
--dont-replace
Do not replace the format if it already exists
remove_format
calibredb remove_format [options] id fmt
Remove the format fmt from the logical book identied by id. You can get id by using the search command. fmt should
be a le extension like LRF or TXT or EPUB. If the logical book does not have fmt available, do nothing.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
show_metadata
calibredb show_metadata [options] id
Show the metadata stored in the calibre database for the book identied by id. id is an id number from the search
command.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--as-opf
Print metadata in OPF form (XML)
316 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
set_metadata
calibredb set_metadata [options] book_id [/path/to/metadata.opf]
Set the metadata stored in the calibre database for the book identied by book_id from the OPF le metadata.opf. book_id
is a book id number from the search command. You can get a quick feel for the OPF format by using the –as-opf switch
to the show_metadata command. You can also set the metadata of individual elds with the –eld option. If you use the
–eld option, there is no need to specify an OPF le.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--field, -f
The eld to set. Format is eld_name:value, for example: --field (page 317) tags:tag1,tag2. Use
--list-fields (page 317) to get a list of all eld names. You can specify this option multiple times to set
multiple elds. Note: For languages you must use the ISO639 language codes (e.g. en for English, fr for French
and so on). For identiers, the syntax is --field (page 317) identiers:isbn:XXXX,doi:YYYYY. For boolean
(yes/no) elds use true and false or yes and no.
--list-fields, -l
List the metadata eld names that can be used with the --field (page 317) option
export
calibredb export [options] ids
Export the books specied by ids (a comma separated list) to the lesystem. The export operation saves all formats of
the book, its cover and metadata (in an OPF le). Any extra data les associated with the book are also saved. You can
get id numbers from the search command.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--all
Export all books in database, ignoring the list of ids.
--dont-asciiize
Have calibre convert all non English characters into English equivalents for the le names. This is useful if saving
to a legacy lesystem without full support for Unicode lenames. Specifying this switch will turn this behavior o.
--dont-save-cover
Normally, calibre will save the cover in a separate le along with the actual e-book les. Specifying this switch will
turn this behavior o.
--dont-save-extra-files
Save any data les associated with the book when saving the book Specifying this switch will turn this behavior o.
--dont-update-metadata
Normally, calibre will update the metadata in the saved les from what is in the calibre library. Makes saving to
disk slower. Specifying this switch will turn this behavior o.
--dont-write-opf
Normally, calibre will write the metadata into a separate OPF le along with the actual e-book les. Specifying
this switch will turn this behavior o.
13.1. Documented commands 317
calibre User Manual, Release 7.19.0
--formats
Comma separated list of formats to save for each book. By default all available formats are saved.
--progress
Report progress
--replace-whitespace
Replace whitespace with underscores.
--single-dir
Export all books into a single folder
--template
The template to control the lename and folder structure of the saved les. Default is "{author_sort}/{title}/{title}
- {authors}" which will save books into a per-author subfolder with lenames containing title and author. Avail-
able controls are: {author_sort, authors, id, isbn, languages, last_modied, pubdate, publisher, rating, series, se-
ries_index, tags, timestamp, title}
--timefmt
The format in which to display dates. %d - day, %b - month, %m - month number, %Y - year. Default is: %b, %Y
--to-dir
Export books to the specied folder. Default is .
--to-lowercase
Convert paths to lowercase.
catalog
calibredb catalog /path/to/destination.(csv|epub|mobi|xml...) [options]
Export a catalog in format specied by path/to/destination extension. Options control how entries are displayed in the
generated catalog output. Note that dierent catalog formats support dierent sets of options. To see the dierent
options, specify the name of the output le and then the –help option.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--ids, -i
Comma-separated list of database IDs to catalog. If declared, --search (page 318) is ignored. Default: all
--search, -s
Filter the results by the search query. For the format of the search query, please see the search-related documen-
tation in the User Manual. Default: no ltering
--verbose, -v
Show detailed output information. Useful for debugging
318 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
Epub Options
--catalog-title
Title of generated catalog used as title in metadata. Default: 'My Books' Applies to: AZW3, EPUB, MOBI
output formats
--cross-reference-authors
Create cross-references in Authors section for books with multiple authors. Default: 'False' Applies to: AZW3,
EPUB, MOBI output formats
--debug-pipeline
Save the output from dierent stages of the conversion pipeline to the specied folder. Useful if you are unsure
at which stage of the conversion process a bug is occurring. Default: 'None' Applies to: AZW3, EPUB, MOBI
output formats
--exclude-genre
Regex describing tags to exclude as genres. Default: '[.+]|^+$' excludes bracketed tags, e.g. '[Project Guten-
berg]', and '+', the default tag for read books. Applies to: AZW3, EPUB, MOBI output formats
--exclusion-rules
Species the rules used to exclude books from the generated catalog. The model for an exclusion rule
is either ('<rule name>','Tags','<comma-separated list of tags>') or ('<rule name>','<custom col-
umn>','<pattern>'). For example: (('Archived books','#status','Archived'),) will exclude a book with a
value of 'Archived' in the custom column 'status'. When multiple rules are dened, all rules will be applied.
Default: "(('Catalogs','Tags','Catalog'),)" Applies to: AZW3, EPUB, MOBI output formats
--generate-authors
Include 'Authors' section in catalog. Default: 'False' Applies to: AZW3, EPUB, MOBI output formats
--generate-descriptions
Include 'Descriptions' section in catalog. Default: 'False' Applies to: AZW3, EPUB, MOBI output formats
--generate-genres
Include 'Genres' section in catalog. Default: 'False' Applies to: AZW3, EPUB, MOBI output formats
--generate-recently-added
Include 'Recently Added' section in catalog. Default: 'False' Applies to: AZW3, EPUB, MOBI output formats
--generate-series
Include 'Series' section in catalog. Default: 'False' Applies to: AZW3, EPUB, MOBI output formats
--generate-titles
Include 'Titles' section in catalog. Default: 'False' Applies to: AZW3, EPUB, MOBI output formats
--genre-source-field
Source eld for 'Genres' section. Default: 'Tags' Applies to: AZW3, EPUB, MOBI output formats
--header-note-source-field
Custom eld containing note text to insert in Description header. Default: '' Applies to: AZW3, EPUB, MOBI
output formats
--merge-comments-rule
#<custom eld>:[before|after]:[True|False] specifying: <custom eld> Custom eld containing notes to merge with
comments [before|after] Placement of notes with respect to comments [True|False] - A horizontal rule is inserted
between notes and comments Default: '::' Applies to: AZW3, EPUB, MOBI output formats
13.1. Documented commands 319
calibre User Manual, Release 7.19.0
--output-profile
Species the output prole. In some cases, an output prole is required to optimize the catalog for the device. For
example, 'kindle' or 'kindle_dx' creates a structured Table of Contents with Sections and Articles. Default:
'None' Applies to: AZW3, EPUB, MOBI output formats
--prefix-rules
Species the rules used to include prexes indicating read books, wishlist items and other user-specied pre-
xes. The model for a prex rule is ('<rule name>','<source eld>','<pattern>','<prex>'). When multiple
rules are dened, the rst matching rule will be used. Default: "(('Read books','tags','+',''),('Wishlist
item','tags','Wishlist','×'))" Applies to: AZW3, EPUB, MOBI output formats
--preset
Use a named preset created with the GUI catalog builder. A preset species all settings for building a catalog.
Default: 'None' Applies to: AZW3, EPUB, MOBI output formats
--thumb-width
Size hint (in inches) for book covers in catalog. Range: 1.0 - 2.0 Default: '1.0' Applies to: AZW3, EPUB, MOBI
output formats
--use-existing-cover
Replace existing cover when generating the catalog. Default: 'False' Applies to: AZW3, EPUB, MOBI output
formats
saved_searches
calibredb saved_searches [options] (list|add|remove)
Manage the saved searches stored in this database. If you try to add a query with a name that already exists, it will be
replaced.
Syntax for adding:
calibredb saved_searches add search_name search_expression
Syntax for removing:
calibredb saved_searches remove search_name
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
add_custom_column
calibredb add_custom_column [options] label name datatype
Create a custom column. label is the machine friendly name of the column. Should not contain spaces or colons. name
is the human friendly name of the column. datatype is one of: bool, comments, composite, datetime, enumeration, oat,
int, rating, series, text
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--display
A dictionary of options to customize how the data in this column will be interpreted. This is a JSON string. For enu-
meration columns, use --display (page 320)"{\ "enum_values\ ":[\ "val1\ ", \ "val2\ "]}" There are many
320 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
options that can go into the display variable.The options by column type are: composite: composite_template, com-
posite_sort, make_category,contains_html, use_decorations datetime: date_format enumeration: enum_values,
enum_colors, use_decorations int, oat: number_format text: is_names, use_decorations The best way to nd le-
gal combinations is to create a custom column of the appropriate type in the GUI then look at the backup OPF
for a book (ensure that a new OPF has been created since the column was added). You will see the JSON for the
"display" for the new column in the OPF.
--is-multiple
This column stores tag like data (i.e. multiple comma separated values). Only applies if datatype is text.
custom_columns
calibredb custom_columns [options]
List available custom columns. Shows column labels and ids.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--details, -d
Show details for each column.
remove_custom_column
calibredb remove_custom_column [options] label
Remove the custom column identied by label. You can see available columns with the custom_columns command.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--force, -f
Do not ask for conrmation
set_custom
calibredb set_custom [options] column id value
Set the value of a custom column for the book identied by id. You can get a list of ids using the search command. You
can get a list of custom column names using the custom_columns command.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--append, -a
If the column stores multiple values, append the specied values to the existing ones, instead of replacing them.
13.1. Documented commands 321
calibre User Manual, Release 7.19.0
restore_database
calibredb restore_database [options]
Restore this database from the metadata stored in OPF les in each folder of the calibre library. This is useful if your
metadata.db le has been corrupted.
WARNING: This command completely regenerates your database. You will lose all saved searches, user categories,
plugboards, stored per-book conversion settings, and custom recipes. Restored metadata will only be as accurate as what
is found in the OPF les.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--really-do-it, -r
Really do the recovery. The command will not run unless this option is specied.
check_library
calibredb check_library [options]
Perform some checks on the lesystem representing a library. Reports are invalid_titles, extra_titles, invalid_authors,
extra_authors, missing_formats, extra_formats, extra_les, missing_covers, extra_covers, failed_folders
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--csv, -c
Output in CSV
--ignore_extensions, -e
Comma-separated list of extensions to ignore. Default: all
--ignore_names, -n
Comma-separated list of names to ignore. Default: all
--report, -r
Comma-separated list of reports. Default: all
--vacuum-fts-db
Vacuum the full text search database. This can be very slow and memory intensive, depending on the size of the
database.
list_categories
calibredb list_categories [options]
Produce a report of the category information in the database. The information is the equivalent of what is shown in the
Tag browser.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--categories, -r
Comma-separated list of category lookup names. Default: all
322 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--csv, -c
Output in CSV
--dialect
The type of CSV le to produce. Choices: excel, excel-tab, unix
--item_count, -i
Output only the number of items in a category instead of the counts per item within the category
--width, -w
The maximum width of a single line in the output. Defaults to detecting screen size.
backup_metadata
calibredb backup_metadata [options]
Backup the metadata stored in the database into individual OPF les in each books folder. This normally happens auto-
matically, but you can run this command to force re-generation of the OPF les, with the –all option.
Note that there is normally no need to do this, as the OPF les are backed up automatically, every time metadata is
changed.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--all
Normally, this command only operates on books that have out of date OPF les. This option makes it operate on
all books.
clone
calibredb clone path/to/new/library
Create a clone of the current library. This creates a new, empty library that has all the same custom columns, Virtual
libraries and other settings as the current library.
The cloned library will contain no books. If you want to create a full duplicate, including all books, then simply use your
lesystem tools to copy the library folder.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
embed_metadata
calibredb embed_metadata [options] book_id
Update the metadata in the actual book les stored in the calibre library from the metadata in the calibre database.
Normally, metadata is updated only when exporting les from calibre, this command is useful if you want the les to be
updated in place. Note that dierent le formats support dierent amounts of metadata. You can use the special value
‘all’ for book_id to update metadata in all books. You can also specify many book ids separated by spaces and id ranges
separated by hyphens. For example: calibredb embed_metadata 1 2 10-15 23
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
13.1. Documented commands 323
calibre User Manual, Release 7.19.0
--only-formats, -f
Only update metadata in les of the specied format. Specify it multiple times for multiple formats. By default, all
formats are updated.
search
calibredb search [options] search expression
Search the library for the specied search term, returning a comma separated list of book ids matching the search
expression. The output format is useful to feed into other commands that accept a list of ids as input.
The search expression can be anything from calibre’s powerful search query language, for example: calibredb
search author:asimov ‘title:”i robot”’
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--limit, -l
The maximum number of results to return. Default is all results.
fts_index
calibredb fts_index [options] enable/disable/status/reindex
Control the Full text search indexing process.
enable
Turns on FTS indexing for this library
disable
Turns o FTS indexing for this library
status
Shows the current indexing status
reindex
Can be used to re-index either particular books or the entire library. To re-index particular books specify the book
ids as additional arguments after the reindex command. If no book ids are specied the entire library is re-indexed.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--indexing-speed
The speed of indexing. Use fast for fast indexing using all your computers resources and slow for less resource
intensive indexing. Note that the speed is reset to slow after every invocation.
--wait-for-completion
Wait till all books are indexed, showing indexing progress periodically
324 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
fts_search
calibredb fts_search [options] search expression
Do a full text search on the entire library or a subset of it.
Whenever you pass arguments to calibredb that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
--do-not-match-on-related-words
Only match on exact words not related words. So correction will not match correcting.
--include-snippets
Include snippets of the text surrounding each match. Note that this makes searching much slower.
--indexing-threshold
How much of the library must be indexed before searching is allowed, as a percentage. Defaults to 90
--match-end-marker
The marker used to indicate the end of a matched word inside a snippet
--match-start-marker
The marker used to indicate the start of a matched word inside a snippet
--output-format
The format to output the search results in. Either "text" for plain text or "json" for JSON output.
--restrict-to
Restrict the searched books, either using a search expression or ids. For example: ids:1,2,3 to restrict by ids or
search:tag:foo to restrict to books having the tag foo.
13.1.7 ebook-convert
ebook-convert input_file output_file [options]
Convert an e-book from one format to another.
input_le is the input and output_le is the output. Both must be specied as the rst two arguments to the command.
The output e-book format is guessed from the le extension of output_le. output_le can also be of the special format
.EXT where EXT is the output le extension. In this case, the name of the output le is derived from the name of the
input le. Note that the lenames must not start with a hyphen. Finally, if output_le has no extension, then it is treated
as a folder and an “open e-book” (OEB) consisting of HTML les is written to that folder. These les are the les that
would normally have been passed to the output plugin.
After specifying the input and output le you can customize the conversion by specifying various options. The available
options depend on the input and output le types. To get help on them specify the input and output le and then use the
-h option.
For full documentation of the conversion system see E-book conversion (page 59)
Whenever you pass arguments to ebook-convert that have spaces in them, enclose the arguments in quotation marks.
For example: “/some path/with spaces”
The options and default values for the options change depending on both the input and output formats, so you should
always check with:
13.1. Documented commands 325
calibre User Manual, Release 7.19.0
ebook-convert myfile.input_format myfile.output_format -h
Below are the options that are common to all conversion, followed by the options specic to every input and output format.
Look and Feel (page 328)
Heuristic Processing (page 330)
Search and Replace (page 331)
Structure Detection (page 331)
Table of Contents (page 332)
Metadata (page 333)
Debug (page 334)
AZW4 Input Options (page 334)
CHM Input Options (page 334)
Comic Input Options (page 334)
DJVU Input Options (page 335)
DOCX Input Options (page 336)
EPUB Input Options (page 336)
FB2 Input Options (page 336)
HTLZ Input Options (page 336)
HTML Input Options (page 336)
LIT Input Options (page 337)
LRF Input Options (page 337)
MOBI Input Options (page 337)
ODT Input Options (page 337)
PDB Input Options (page 338)
PDF Input Options (page 338)
PML Input Options (page 338)
RB Input Options (page 339)
RTF Input Options (page 339)
Recipe Input Options (page 339)
SNB Input Options (page 340)
TCR Input Options (page 340)
TXT Input Options (page 340)
AZW3 Output Options (page 341)
DOCX Output Options (page 341)
EPUB Output Options (page 342)
326 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
FB2 Output Options (page 343)
HTML Output Options (page 344)
HTMLZ Output Options (page 344)
LIT Output Options (page 344)
LRF Output Options (page 344)
MOBI Output Options (page 345)
OEB Output Options (page 346)
PDB Output Options (page 346)
PDF Output Options (page 347)
PML Output Options (page 349)
RB Output Options (page 349)
RTF Output Options (page 349)
SNB Output Options (page 349)
TCR Output Options (page 350)
TXT Output Options (page 350)
TXTZ Output Options (page 351)
--help, -h
show this help message and exit
--input-profile
Specify the input prole. The input prole gives the conversion system information on how to interpret various
information in the input document. For example resolution dependent lengths (i.e. lengths in pixels). Choices are:
cybookg3, cybook_opus, default, hanlinv3, hanlinv5, illiad, irexdr1000, irexdr800, kindle, msreader, mobipocket,
nook, sony, sony300, sony900
--list-recipes
List builtin recipe names. You can create an e-book from a builtin recipe like this: ebook-convert "Recipe
Name.recipe" output.epub
--output-profile
Specify the output prole. The output prole tells the conversion system how to optimize the created doc-
ument for the specied device. In some cases, an output prole can be used to optimize the output for
a particular device, but this is rarely necessary. Choices are:cybookg3, cybook_opus, default, generic_eink,
generic_eink_hd, generic_eink_large, hanlinv3, hanlinv5, illiad, ipad, ipad3, irexdr1000, irexdr800, jetbook5, kin-
dle, kindle_dx, kindle_re, kindle_oasis, kindle_pw, kindle_pw3, kindle_scribe, kindle_voyage, kobo, msreader,
mobipocket, nook, nook_color, nook_hd_plus, pocketbook_inkpad3, pocketbook_lux, pocketbook_hd, pocket-
book_900, pocketbook_pro_912, galaxy, sony, sony300, sony900, sony-landscape, sonyt3, tablet
--version
show program's version number and exit
13.1. Documented commands 327
calibre User Manual, Release 7.19.0
Look and Feel
Options to control the look and feel of the output
--asciiize
Transliterate Unicode characters to an ASCII representation. Use with care because this will replace Unicode
characters with ASCII. For instance it will replace "Pe" with "Pele". Also, note that in cases where there are
multiple representations of a character (characters shared by Chinese and Japanese for instance) the representation
based on the current calibre interface language will be used.
--base-font-size
The base font size in pts. All font sizes in the produced book will be rescaled based on this size. By choosing a
larger size you can make the fonts in the output bigger and vice versa. By default, when the value is zero, the base
font size is chosen based on the output prole you chose.
--change-justification
Change text justication. A value of "left" converts all justied text in the source to left aligned (i.e. unjustied)
text. A value of "justify" converts all unjustied text to justied. A value of "original" (the default) does not
change justication in the source le. Note that only some output formats support justication.
--disable-font-rescaling
Disable all rescaling of font sizes.
--embed-all-fonts
Embed every font that is referenced in the input document but not already embedded. This will search your system
for the fonts, and if found, they will be embedded. Embedding will only work if the format you are converting to
supports embedded fonts, such as EPUB, AZW3, DOCX or PDF. Please ensure that you have the proper license
for embedding the fonts used in this document.
--embed-font-family
Embed the specied font family into the book. This species the "base" font used for the book. If the input
document species its own fonts, they may override this base font. You can use the lter style information option to
remove fonts from the input document. Note that font embedding only works with some output formats, principally
EPUB, AZW3 and DOCX.
--expand-css
By default, calibre will use the shorthand form for various CSS properties such as margin, padding, border, etc.
This option will cause it to use the full expanded form instead. Note that CSS is always expanded when generating
EPUB les with the output prole set to one of the Nook proles as the Nook cannot handle shorthand CSS.
--extra-css
Either the path to a CSS stylesheet or raw CSS. This CSS will be appended to the style rules from the source le,
so it can be used to override those rules.
--filter-css
A comma separated list of CSS properties that will be removed from all CSS style rules. This is useful if the presence
of some style information prevents it from being overridden on your device. For example: font-family,color,margin-
left,margin-right
--font-size-mapping
Mapping from CSS font names to font sizes in pts. An example setting is 12,12,14,16,18,20,22,24. These are the
mappings for the sizes xx-small to xx-large, with the nal size being for huge fonts. The font rescaling algorithm
uses these sizes to intelligently rescale fonts. The default is to use a mapping based on the output prole you chose.
--insert-blank-line
Insert a blank line between paragraphs. Will not work if the source le does not use paragraphs (<p> or <div>
tags).
328 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--insert-blank-line-size
Set the height of the inserted blank lines (in em). The height of the lines between paragraphs will be twice the
value set here.
--keep-ligatures
Preserve ligatures present in the input document. A ligature is a combined character of a pair of characters like
, , et cetera. Most readers do not have support for ligatures in their default fonts, so they are unlikely to
render correctly. By default, calibre will turn a ligature into the corresponding pair of normal characters. Note that
ligatures here mean only unicode ligatures not ligatures created via CSS or font styles. This option will preserve
them instead.
--line-height
The line height in pts. Controls spacing between consecutive lines of text. Only applies to elements that do not
dene their own line height. In most cases, the minimum line height option is more useful. By default no line height
manipulation is performed.
--linearize-tables
Some badly designed documents use tables to control the layout of text on the page. When converted these docu-
ments often have text that runs o the page and other artifacts. This option will extract the content from the tables
and present it in a linear fashion.
--margin-bottom
Set the bottom margin in pts. Default is 5.0. Setting this to less than zero will cause no margin to be set (the margin
setting in the original document will be preserved). Note: Page oriented formats such as PDF and DOCX have
their own margin settings that take precedence.
--margin-left
Set the left margin in pts. Default is 5.0. Setting this to less than zero will cause no margin to be set (the margin
setting in the original document will be preserved). Note: Page oriented formats such as PDF and DOCX have
their own margin settings that take precedence.
--margin-right
Set the right margin in pts. Default is 5.0. Setting this to less than zero will cause no margin to be set (the margin
setting in the original document will be preserved). Note: Page oriented formats such as PDF and DOCX have
their own margin settings that take precedence.
--margin-top
Set the top margin in pts. Default is 5.0. Setting this to less than zero will cause no margin to be set (the margin
setting in the original document will be preserved). Note: Page oriented formats such as PDF and DOCX have
their own margin settings that take precedence.
--minimum-line-height
The minimum line height, as a percentage of the element's calculated font size. calibre will ensure that every
element has a line height of at least this setting, irrespective of what the input document species. Set to zero to
disable. Default is 120%. Use this setting in preference to the direct line height specication, unless you know what
you are doing. For example, you can achieve "double spaced" text by setting this to 240.
--remove-paragraph-spacing
Remove spacing between paragraphs. Also sets an indent on paragraphs of 1.5em. Spacing removal will not work
if the source le does not use paragraphs (<p> or <div> tags).
--remove-paragraph-spacing-indent-size
When calibre removes blank lines between paragraphs, it automatically sets a paragraph indent, to ensure that
paragraphs can be easily distinguished. This option controls the width of that indent (in em). If you set this value
negative, then the indent specied in the input document is used, that is, calibre does not change the indentation.
13.1. Documented commands 329
calibre User Manual, Release 7.19.0
--smarten-punctuation
Convert plain quotes, dashes and ellipsis to their typographically correct equivalents. For details, see https:
//daringfireball.net/projects/smartypants.
--subset-embedded-fonts
Subset all embedded fonts. Every embedded font is reduced to contain only the glyphs used in this document. This
decreases the size of the font les. Useful if you are embedding a particularly large font with lots of unused glyphs.
--transform-css-rules
Path to a le containing rules to transform the CSS styles in this book. The easiest way to create such a le is to
use the wizard for creating rules in the calibre GUI. Access it in the "Look & feel->Transform styles" section of
the conversion dialog. Once you create the rules, you can use the "Export" button to save them to a le.
--transform-html-rules
Path to a le containing rules to transform the HTML in this book. The easiest way to create such a le is to use
the wizard for creating rules in the calibre GUI. Access it in the "Look & feel->Transform HTML" section of the
conversion dialog. Once you create the rules, you can use the "Export" button to save them to a le.
--unsmarten-punctuation
Convert fancy quotes, dashes and ellipsis to their plain equivalents.
Heuristic Processing
Modify the document text and structure using common patterns. Disabled by default. Use –enable-heuristics to enable.
Individual actions can be disabled with the –disable-* options.
--disable-dehyphenate
Analyze hyphenated words throughout the document. The document itself is used as a dictionary to determine
whether hyphens should be retained or removed.
--disable-delete-blank-paragraphs
Remove empty paragraphs from the document when they exist between every other paragraph
--disable-fix-indents
Turn indentation created from multiple non-breaking space entities into CSS indents.
--disable-format-scene-breaks
Left aligned scene break markers are center aligned. Replace soft scene breaks that use multiple blank lines with
horizontal rules.
--disable-italicize-common-cases
Look for common words and patterns that denote italics and italicize them.
--disable-markup-chapter-headings
Detect unformatted chapter headings and sub headings. Change them to h2 and h3 tags. This setting will not create
a TOC, but can be used in conjunction with structure detection to create one.
--disable-renumber-headings
Looks for occurrences of sequential <h1> or <h2> tags. The tags are renumbered to prevent splitting in the middle
of chapter headings.
--disable-unwrap-lines
Unwrap lines using punctuation and other formatting clues.
--enable-heuristics
Enable heuristic processing. This option must be set for any heuristic processing to take place.
330 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--html-unwrap-factor
Scale used to determine the length at which a line should be unwrapped. Valid values are a decimal between 0 and
1. The default is 0.4, just below the median line length. If only a few lines in the document require unwrapping
this value should be reduced
--replace-scene-breaks
Replace scene breaks with the specied text. By default, the text from the input document is used.
Search and Replace
Modify the document text and structure using user dened patterns.
--search-replace
Path to a le containing search and replace regular expressions. The le must contain alternating lines of regular
expression followed by replacement pattern (which can be an empty line). The regular expression must be in the
Python regex syntax and the le must be UTF-8 encoded.
--sr1-replace
Replacement to replace the text found with sr1-search.
--sr1-search
Search pattern (regular expression) to be replaced with sr1-replace.
--sr2-replace
Replacement to replace the text found with sr2-search.
--sr2-search
Search pattern (regular expression) to be replaced with sr2-replace.
--sr3-replace
Replacement to replace the text found with sr3-search.
--sr3-search
Search pattern (regular expression) to be replaced with sr3-replace.
Structure Detection
Control auto-detection of document structure.
--add-alt-text-to-img
When an <img> tag has no alt attribute, check the associated image le for metadata that species alternate text,
and use it to ll in the alt attribute. The alt attribute is used by screen readers for assisting the visually challenged.
--chapter
An XPath expression to detect chapter titles. The default is to consider <h1> or <h2> tags that contain the words
"chapter", "book", "section", "prologue", "epilogue" or "part" as chapter titles as well as any tags that have
class="chapter". The expression used must evaluate to a list of elements. To disable chapter detection, use the
expression "/". See the XPath Tutorial in the calibre User Manual for further help on using this feature.
--chapter-mark
Specify how to mark detected chapters. A value of "pagebreak" will insert page breaks before chapters. A value
of "rule" will insert a line before chapters. A value of "none" will disable chapter marking and a value of "both"
will use both page breaks and lines to mark chapters.
13.1. Documented commands 331
calibre User Manual, Release 7.19.0
--disable-remove-fake-margins
Some documents specify page margins by specifying a left and right margin on each individual paragraph. calibre
will try to detect and remove these margins. Sometimes, this can cause the removal of margins that should not have
been removed. In this case you can disable the removal.
--insert-metadata
Insert the book metadata at the start of the book. This is useful if your e-book reader does not support display-
ing/searching metadata directly.
--page-breaks-before
An XPath expression. Page breaks are inserted before the specied elements. To disable use the expression: /
--prefer-metadata-cover
Use the cover detected from the source le in preference to the specied cover.
--remove-first-image
Remove the rst image from the input e-book. Useful if the input document has a cover image that is not identied
as a cover. In this case, if you set a cover in calibre, the output document will end up with two cover images if you
do not specify this option.
--start-reading-at
An XPath expression to detect the location in the document at which to start reading. Some e-book reading pro-
grams (most prominently the Kindle) use this location as the position at which to open the book. See the XPath
tutorial in the calibre User Manual for further help using this feature.
Table of Contents
Control the automatic generation of a Table of Contents. By default, if the source le has a Table of Contents, it will be
used in preference to the automatically generated one.
--duplicate-links-in-toc
When creating a TOC from links in the input document, allow duplicate entries, i.e. allow more than one entry
with the same text, provided that they point to a dierent location.
--level1-toc
XPath expression that species all tags that should be added to the Table of Contents at level one. If this is specied,
it takes precedence over other forms of auto-detection. See the XPath Tutorial in the calibre User Manual for
examples.
--level2-toc
XPath expression that species all tags that should be added to the Table of Contents at level two. Each entry is
added under the previous level one entry. See the XPath Tutorial in the calibre User Manual for examples.
--level3-toc
XPath expression that species all tags that should be added to the Table of Contents at level three. Each entry is
added under the previous level two entry. See the XPath Tutorial in the calibre User Manual for examples.
--max-toc-links
Maximum number of links to insert into the TOC. Set to 0 to disable. Default is: 50. Links are only added to the
TOC if less than the threshold number of chapters were detected.
--no-chapters-in-toc
Don't add auto-detected chapters to the Table of Contents.
332 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--toc-filter
Remove entries from the Table of Contents whose titles match the specied regular expression. Matching entries
and all their children are removed.
--toc-threshold
If fewer than this number of chapters is detected, then links are added to the Table of Contents. Default: 6
--use-auto-toc
Normally, if the source le already has a Table of Contents, it is used in preference to the auto-generated one. With
this option, the auto-generated one is always used.
Metadata
Options to set metadata in the output
--author-sort
String to be used when sorting by author.
--authors
Set the authors. Multiple authors should be separated by ampersands.
--book-producer
Set the book producer.
--comments
Set the e-book description.
--cover
Set the cover to the specied le or URL
--isbn
Set the ISBN of the book.
--language
Set the language.
--pubdate
Set the publication date (assumed to be in the local timezone, unless the timezone is explicitly specied)
--publisher
Set the e-book publisher.
--rating
Set the rating. Should be a number between 1 and 5.
--read-metadata-from-opf, --from-opf, -m
Read metadata from the specied OPF le. Metadata read from this le will override any metadata in the source
le.
--series
Set the series this e-book belongs to.
--series-index
Set the index of the book in this series.
--tags
Set the tags for the book. Should be a comma separated list.
13.1. Documented commands 333
calibre User Manual, Release 7.19.0
--timestamp
Set the book timestamp (no longer used anywhere)
--title
Set the title.
--title-sort
The version of the title to be used for sorting.
Debug
Options to help with debugging the conversion
--debug-pipeline, -d
Save the output from dierent stages of the conversion pipeline to the specied folder. Useful if you are unsure at
which stage of the conversion process a bug is occurring.
--verbose, -v
Level of verbosity. Specify multiple times for greater verbosity. Specifying it twice will result in full verbosity,
once medium verbosity and zero times least verbosity.
AZW4 Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
CHM Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
Comic Input Options
--colors
Reduce the number of colors used in the image. This works only if you choose the PNG output format. It is useful
to reduce le sizes. Set to zero to turn o. Maximum value is 256. It is o by default.
--comic-image-size
Specify the image size as width x height pixels, for example: 123x321. Normally, an image size is automatically
calculated from the output prole, this option overrides it.
--despeckle
Enable Despeckle. Reduces speckle noise. May greatly increase processing time.
--disable-trim
Disable trimming of comic pages. For some comics, trimming might remove content as well as borders.
334 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--dont-add-comic-pages-to-toc
When converting a CBC do not add links to each page to the TOC. Note this only applies if the TOC has more
than one section
--dont-grayscale
Do not convert the image to grayscale (black and white)
--dont-normalize
Disable normalize (improve contrast) color range for pictures. Default: False
--dont-sharpen
Disable sharpening.
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
--keep-aspect-ratio
Maintain picture aspect ratio. Default is to ll the screen.
--landscape
Don't split landscape images into two portrait images
--no-process
Apply no processing to the image
--no-sort
Don't sort the les found in the comic alphabetically by name. Instead use the order they were added to the comic.
--output-format
The format that images in the created e-book are converted to. You can experiment to see which format gives you
optimal size and look on your device.
--right2left
Used for right-to-left publications like manga. Causes landscape pages to be split into portrait pages from right to
left.
--wide
Keep aspect ratio and scale image using screen height as image width for viewing in landscape mode.
DJVU Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
13.1. Documented commands 335
calibre User Manual, Release 7.19.0
DOCX Input Options
--docx-inline-subsup
Render superscripts and subscripts so that they do not aect the line height
--docx-no-cover
Normally, if a large image is present at the start of the document that looks like a cover, it will be removed from
the document and used as the cover for created e-book. This option turns o that behavior.
--docx-no-pagebreaks-between-notes
Do not insert a page break after every endnote.
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
EPUB Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
FB2 Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
--no-inline-fb2-toc
Do not insert a Table of Contents at the beginning of the book
HTLZ Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
HTML Input Options
--allow-local-files-outside-root
Normally, resources linked to by the HTML le or its children will only be allowed if they are in a sub-folder of
the original HTML le. This option allows including local les from any location on your computer. This can be a
security risk if you are converting untrusted HTML and expecting to distribute the result of the conversion.
--breadth-first
Traverse links in HTML les breadth rst. Normally, they are traversed depth rst.
336 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--dont-package
Normally this input plugin re-arranges all the input les into a standard folder hierarchy. Only use this option if
you know what you are doing as it can result in various nasty side eects in the rest of the conversion pipeline.
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
--max-levels
Maximum levels of recursion when following links in HTML les. Must be non-negative. 0 implies that no links
in the root HTML le are followed. Default is 5.
LIT Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
LRF Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
MOBI Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
ODT Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
13.1. Documented commands 337
calibre User Manual, Release 7.19.0
PDB Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
PDF Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
--new-pdf-engine
Use the new, experimental, PDF conversion engine.
--no-images
Do not extract images from the document
--pdf-footer-regex
Regular expression to remove lines at the bottom of a page. This only looks at the last line of a page and works
only with the new PDF engine.
--pdf-footer-skip
Skip everything to the specied number of pixels at the bottom of a page. Negative numbers mean auto-detect and
remove footers, zero means do not remove footers and positive numbers mean remove footers that appear below
that many pixels from the bottom of the page. Works only with the new PDF engine.
--pdf-header-regex
Regular expression to remove lines at the top of a page. This only looks at the rst line of a page and works only
with the new PDF engine.
--pdf-header-skip
Skip everything to the specied number of pixels at the top of a page. Negative numbers mean auto-detect and
remove headers, zero means do not remove headers and positive numbers mean remove headers that appear above
that many pixels from the top of the page. Works only with the new PDF engine.
--unwrap-factor
Scale used to determine the length at which a line should be unwrapped. Valid values are a decimal between 0 and
1. The default is 0.45, just below the median line length.
PML Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
338 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
RB Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
RTF Input Options
--ignore-wmf
Ignore WMF images instead of replacing them with a placeholder image.
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
Recipe Input Options
--dont-download-recipe
Do not download latest version of builtin recipes from the calibre server
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
--lrf
Optimize fetching for subsequent conversion to LRF.
--password
Password for sites that require a login to access content.
--recipe-specific-option
Recipe specic options. Syntax is option_name:value. For example: --recipe-specific-option
(page 339) = date:2030-11-31. Can be specied multiple times to set dierent options. To see a list of all
available options for a recipe, use --recipe-specific-option (page 339) = list.
--test
Useful for recipe development. Forces max_articles_per_feed to 2 and downloads at most 2 feeds. You can change
the number of feeds and articles by supplying optional arguments. For example: --test (page 339) 3 1 will
download at most 3 feeds and only 1 article per feed.
--username
Username for sites that require a login to access content.
13.1. Documented commands 339
calibre User Manual, Release 7.19.0
SNB Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
TCR Input Options
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
TXT Input Options
--formatting-type
Formatting used within the document. * auto: Automatically decide which formatting processor to use * plain:
No formatting * heuristic: Use heuristics to determine chapter headings, italics, etc. * textile: Use the Textile
markup language * markdown: Use the Markdown markup language To learn more about Markdown see https:
//daringfireball.net/projects/markdown/
--input-encoding
Specify the character encoding of the input document. If set this option will override any encoding declared by the
document itself. Particularly useful for documents that do not declare an encoding or that have erroneous encoding
declarations.
--markdown-extensions
Enable extensions to Markdown syntax. Extensions are formatting that is not part of the standard Markdown
format. The extensions enabled by default: footnotes, tables, toc. To learn more about Markdown extensions,
see https://python-markdown.github.io/extensions/ This should be a comma separated list of extensions to enable:
* abbr: Abbreviations * admonition: Support admonitions * attr_list: Add attribute to HTML tags * codehilite:
Add code highlighting via Pygments * def_list: Denition lists * extra: Enables various common extensions *
fenced_code: Alternative code block syntax * footnotes: Footnotes * legacy_attrs: Use legacy element attributes
* legacy_em: Use legacy underscore handling for connected words * meta: Metadata in the document * nl2br:
Treat newlines as hard breaks * sane_lists: Do not allow mixing list types * smarty: Use Markdown's internal
smartypants parser * tables: Support tables * toc: Generate a table of contents * wikilinks: Wiki style links
--paragraph-type
Paragraph structure to assume. The value of "o" is useful for formatted documents such as Markdown or Textile.
Choices are: * auto: Try to auto detect paragraph type * block: Treat a blank line as a paragraph break * single:
Assume every line is a paragraph * print: Assume every line starting with 2+ spaces or a tab starts a paragraph *
unformatted: Most lines have hard line breaks, few/no blank lines or indents * o: Don't modify the paragraph
structure
--preserve-spaces
Normally extra spaces are condensed into a single space. With this option all spaces will be displayed.
--txt-in-remove-indents
Normally extra space at the beginning of lines is retained. With this option they will be removed.
340 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
AZW3 Output Options
--dont-compress
Disable compression of the le contents.
--extract-to
Extract the contents of the generated AZW3 le to the specied folder. The contents of the folder are rst deleted,
so be careful.
--mobi-toc-at-start
When adding the Table of Contents to the book, add it at the start of the book instead of the end. Not recommended.
--no-inline-toc
Don't add Table of Contents to the book. Useful if the book has its own table of contents.
--prefer-author-sort
When present, use author sort eld as author.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--share-not-sync
Enable sharing of book content via Facebook etc. on the Kindle. WARNING: Using this feature means that the
book will not auto sync its last read position on multiple devices. Complain to Amazon.
--toc-title
Title for any generated inline table of contents.
DOCX Output Options
--docx-custom-page-size
Custom size of the document. Use the form width x height, for example: 123x321 to specify the width and height
(in pts). This overrides any specied page-size.
--docx-no-cover
Do not insert the book cover as an image at the start of the document. If you use this option, the book cover will
be discarded.
--docx-no-toc
Do not insert the table of contents as a page at the start of the document.
--docx-page-margin-bottom
The size of the bottom page margin, in pts. Default is 72pt. Overrides the common bottom page margin setting,
unless set to zero.
--docx-page-margin-left
The size of the left page margin, in pts. Default is 72pt. Overrides the common left page margin setting.
--docx-page-margin-right
The size of the right page margin, in pts. Default is 72pt. Overrides the common right page margin setting, unless
set to zero.
--docx-page-margin-top
The size of the top page margin, in pts. Default is 72pt. Overrides the common top page margin setting, unless set
to zero.
13.1. Documented commands 341
calibre User Manual, Release 7.19.0
--docx-page-size
The size of the page. Default is letter. Choices are ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'b0', 'b1',
'b2', 'b3', 'b4', 'b5', 'b6', 'legal', 'letter']
--extract-to
Extract the contents of the generated DOCX le to the specied folder. The contents of the folder are rst deleted,
so be careful.
--preserve-cover-aspect-ratio
Preserve the aspect ratio of the cover image instead of stretching it out to cover the entire page.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
EPUB Output Options
--dont-split-on-page-breaks
Turn o splitting at page breaks. Normally, input les are automatically split at every page break into two les.
This gives an output e-book that can be parsed faster and with less resources. However, splitting is slow and if your
source le contains a very large number of page breaks, you should turn o splitting on page breaks.
--epub-flatten
This option is needed only if you intend to use the EPUB with FBReaderJ. It will atten the le system inside the
EPUB, putting all les into the top level.
--epub-inline-toc
Insert an inline Table of Contents that will appear as part of the main book content.
--epub-max-image-size
The maximum image size (width x height). A value of none means use the screen size from the output prole. A
value of prole means no maximum size is specied. For example, a value of 100x200 will cause all images to
be resized so that their width is no more than 100 pixels and their height is no more than 200 pixels. Note that
this only aects the size of the actual image les themselves. Any given image may be rendered at a dierent size
depending on the styling applied to it in the document.
--epub-toc-at-end
Put the inserted inline Table of Contents at the end of the book instead of the start.
--epub-version
The version of the EPUB le to generate. EPUB 2 is the most widely compatible, only use EPUB 3 if you know
you actually need it.
--extract-to
Extract the contents of the generated EPUB le to the specied folder. The contents of the folder are rst deleted,
so be careful.
--flow-size
Split all HTML les larger than this size (in KB). This is necessary as most EPUB readers cannot handle large le
sizes. The default of 260KB is the size required for Adobe Digital Editions. Set to 0 to disable size based splitting.
--no-default-epub-cover
Normally, if the input le has no cover and you don't specify one, a default cover is generated with the title, authors,
etc. This option disables the generation of this cover.
342 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--no-svg-cover
Do not use SVG for the book cover. Use this option if your EPUB is going to be used on a device that does not
support SVG, like the iPhone or the JetBook Lite. Without this option, such devices will display the cover as a
blank page.
--preserve-cover-aspect-ratio
When using an SVG cover, this option will cause the cover to scale to cover the available screen area, but still
preserve its aspect ratio (ratio of width to height). That means there may be white borders at the sides or top and
bottom of the image, but the image will never be distorted. Without this option the image may be slightly distorted,
but there will be no borders.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--toc-title
Title for any generated inline table of contents.
FB2 Output Options
--fb2-genre
Genre for the book. Choices: sf_history, sf_action, sf_epic, sf_heroic, sf_detective, sf_cyberpunk, sf_space,
sf_social, sf_horror, sf_humor, sf_fantasy, sf, det_classic, det_police, det_action, det_irony, det_history,
det_espionage, det_crime, det_political, det_maniac, det_hard, thriller, detective, prose_classic, prose_history,
prose_contemporary, prose_counter, prose_rus_classic, prose_su_classics, love_contemporary, love_history,
love_detective, love_short, love_erotica, adv_western, adv_history, adv_indian, adv_maritime, adv_geo,
adv_animal, adventure, child_tale, child_verse, child_prose, child_sf, child_det, child_adv, child_education,
children, poetry, dramaturgy, antique_ant, antique_european, antique_russian, antique_east, antique_myths, an-
tique, sci_history, sci_psychology, sci_culture, sci_religion, sci_philosophy, sci_politics, sci_business, sci_juris,
sci_linguistic, sci_medicine, sci_phys, sci_math, sci_chem, sci_biology, sci_tech, science, comp_www,
comp_programming, comp_hard, comp_soft, comp_db, comp_osnet, computers, ref_encyc, ref_dict, ref_ref,
ref_guide, reference, nonf_biography, nonf_publicism, nonf_criticism, design, nonction, religion_rel, reli-
gion_esoterics, religion_self, religion, humor_anecdote, humor_prose, humor_verse, humor, home_cooking,
home_pets, home_crafts, home_entertain, home_health, home_garden, home_diy, home_sport, home_sex, home
See: http://www.fictionbook.org/index.php/Eng:FictionBook_2.1_genres for a complete list with descriptions.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--sectionize
Specify how sections are created: * nothing: A single section * les: Section per le * toc: Section per entry in the
ToC If ToC based generation fails, adjust the "Structure detection" and/or "Table of Contents" settings (turn on
"Force use of auto-generated Table of Contents").
13.1. Documented commands 343
calibre User Manual, Release 7.19.0
HTML Output Options
--extract-to
Extract the contents of the generated ZIP le to the specied folder. WARNING: The contents of the folder will
be deleted.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--template-css
CSS le used for the output instead of the default le
--template-html
Template used for the generation of the HTML contents of the book instead of the default le
--template-html-index
Template used for generation of the HTML index le instead of the default le
HTMLZ Output Options
--htmlz-class-style
How to handle the CSS when using css-type = 'class'. Default is external. external: Use an external CSS le
inline: Use a <style> tag in the HTML le
--htmlz-css-type
Specify the handling of CSS. Default is class. class: Use CSS classes inline: Use the style attribute tag: Use HTML
tags wherever possible
--htmlz-title-filename
If set this option causes the le name of the HTML le inside the HTMLZ archive to be based on the book title.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
LIT Output Options
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
LRF Output Options
--enable-autorotation
Enable auto-rotation of images that are wider than the screen width.
--header
Add a header to all the pages with title and author.
--header-format
Set the format of the header. %a is replaced by the author and %t by the title. Default is %t by %a
344 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--header-separation
Add extra spacing below the header. Default is 0 pt.
--minimum-indent
Minimum paragraph indent (the indent of the rst line of a paragraph) in pts. Default: 0
--mono-family
The monospace family of fonts to embed
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--render-tables-as-images
This option has no eect
--sans-family
The sans-serif family of fonts to embed
--serif-family
The serif family of fonts to embed
--text-size-multiplier-for-rendered-tables
Multiply the size of text in rendered tables by this factor. Default is 1.0
--wordspace
Set the space between words in pts. Default is 2.5
MOBI Output Options
--dont-compress
Disable compression of the le contents.
--extract-to
Extract the contents of the generated MOBI le to the specied folder. The contents of the folder are rst deleted,
so be careful.
--mobi-file-type
By default calibre generates MOBI les that contain the old MOBI 6 format. This format is compatible with all
devices. However, by changing this setting, you can tell calibre to generate MOBI les that contain both MOBI 6
and the new KF8 format, or only the new KF8 format. KF8 has more features than MOBI 6, but only works with
newer Kindles. Allowed values: old, both, new
--mobi-ignore-margins
Ignore margins in the input document. If False, then the MOBI output plugin will try to convert margins specied
in the input document, otherwise it will ignore them.
--mobi-keep-original-images
By default calibre converts all images to JPEG format in the output MOBI le. This is for maximum compatibility
as some older MOBI viewers have problems with other image formats. This option tells calibre not to do this.
Useful if your document contains lots of GIF/PNG images that become very large when converted to JPEG.
--mobi-toc-at-start
When adding the Table of Contents to the book, add it at the start of the book instead of the end. Not recommended.
13.1. Documented commands 345
calibre User Manual, Release 7.19.0
--no-inline-toc
Don't add Table of Contents to the book. Useful if the book has its own table of contents.
--personal-doc
Tag for MOBI les to be marked as personal documents. This option has no eect on the conversion. It is used
only when sending MOBI les to a device. If the le being sent has the specied tag, it will be marked as a personal
document when sent to the Kindle.
--prefer-author-sort
When present, use author sort eld as author.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--share-not-sync
Enable sharing of book content via Facebook etc. on the Kindle. WARNING: Using this feature means that the
book will not auto sync its last read position on multiple devices. Complain to Amazon.
--toc-title
Title for any generated inline table of contents.
OEB Output Options
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
PDB Output Options
--format, -f
Format to use inside the PDB container. Choices are: ['doc', 'ereader', 'ztxt']
--inline-toc
Add Table of Contents to beginning of the book.
--pdb-output-encoding
Specify the character encoding of the output document. The default is cp1252. Note: This option is not honored
by all formats.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
346 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
PDF Output Options
--custom-size
Custom size of the document. Use the form width x height e.g. 123x321 to specify the width and height. This
overrides any specied paper-size.
--paper-size
The size of the paper. This size will be overridden when a non default output prole is used. Default is letter.
Choices are a0, a1, a2, a3, a4, a5, a6, b0, b1, b2, b3, b4, b5, b6, legal, letter
--pdf-add-toc
Add a Table of Contents at the end of the PDF that lists page numbers. Useful if you want to print out the PDF. If
this PDF is intended for electronic use, use the PDF Outline instead.
--pdf-default-font-size
The default font size (in pixels)
--pdf-footer-template
An HTML template used to generate footers on every page. The strings _PAGENUM_, _TITLE_, _AUTHOR_
and _SECTION_ will be replaced by their current values.
--pdf-header-template
An HTML template used to generate headers on every page. The strings _PAGENUM_, _TITLE_, _AUTHOR_
and _SECTION_ will be replaced by their current values.
--pdf-hyphenate
Break long words at the end of lines. This can give the text at the right margin a more even appearance. Note that
depending on the fonts used this option can break the copying of text from the PDF le.
--pdf-mark-links
Surround all links with a red box, useful for debugging.
--pdf-mono-family
The font family used to render monospace fonts. Will work only if the font is available system-wide.
--pdf-mono-font-size
The default font size for monospaced text (in pixels)
--pdf-no-cover
Do not insert the book cover as an image at the start of the document. If you use this option, the book cover will
be discarded.
--pdf-odd-even-offset
Shift the text horizontally by the specied oset (in pts). On odd numbered pages, it is shifted to the right and on
even numbered pages to the left. Use negative numbers for the opposite eect. Note that this setting is ignored on
pages where the margins are smaller than the specied oset. Shifting is done by setting the PDF CropBox, not all
software respects the CropBox.
--pdf-page-margin-bottom
The size of the bottom page margin, in pts. Default is 72pt. Overrides the common bottom page margin setting,
unless set to zero.
--pdf-page-margin-left
The size of the left page margin, in pts. Default is 72pt. Overrides the common left page margin setting.
13.1. Documented commands 347
calibre User Manual, Release 7.19.0
--pdf-page-margin-right
The size of the right page margin, in pts. Default is 72pt. Overrides the common right page margin setting, unless
set to zero.
--pdf-page-margin-top
The size of the top page margin, in pts. Default is 72pt. Overrides the common top page margin setting, unless set
to zero.
--pdf-page-number-map
Adjust page numbers, as needed. Syntax is a JavaScript expression for the page number. For example, "if (n < 3)
0; else n - 3;", where n is current page number.
--pdf-page-numbers
Add page numbers to the bottom of every page in the generated PDF le. If you specify a footer template, it will
take precedence over this option.
--pdf-sans-family
The font family used to render sans-serif fonts. Will work only if the font is available system-wide.
--pdf-serif-family
The font family used to render serif fonts. Will work only if the font is available system-wide.
--pdf-standard-font
The type of font family used to render font for which no font family is specied.
--pdf-use-document-margins
Use the page margins specied in the input document via @page CSS rules. This will cause the margins specied
in the conversion settings to be ignored. If the document does not specify page margins, the conversion settings
will be used as a fallback.
--preserve-cover-aspect-ratio
Preserve the aspect ratio of the cover, instead of stretching it to ll the full rst page of the generated PDF.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--toc-title
Title for generated table of contents.
--uncompressed-pdf
Generate an uncompressed PDF, useful for debugging.
--unit, -u
The unit of measure for page sizes. Default is inch. Choices are millimeter, centimeter, point, inch, pica, didot,
cicero, devicepixel Note: This does not override the unit for margins!
--use-profile-size
Instead of using the paper size specied in the PDF Output options, use a paper size corresponding to the current
output prole. Useful if you want to generate a PDF for viewing on a specic device.
348 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
PML Output Options
--full-image-depth
Do not reduce the size or bit depth of images. Images have their size and depth reduced by default to accommodate
applications that can not convert images on their own such as Dropbook.
--inline-toc
Add Table of Contents to beginning of the book.
--pml-output-encoding
Specify the character encoding of the output document. The default is cp1252.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
RB Output Options
--inline-toc
Add Table of Contents to beginning of the book.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
RTF Output Options
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
SNB Output Options
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--snb-dont-indent-first-line
Specify whether or not to insert two space characters to indent the rst line of each paragraph.
--snb-full-screen
Resize all the images for full screen mode.
--snb-hide-chapter-name
Specify whether or not to hide the chapter title for each chapter. Useful for image-only output (eg. comics).
--snb-insert-empty-line
Specify whether or not to insert an empty line between two paragraphs.
--snb-max-line-length
The maximum number of characters per line. This splits on the rst space before the specied value. If no space
is found the line will be broken at the space after and will exceed the specied value. Also, there is a minimum of
25 characters. Use 0 to disable line splitting.
13.1. Documented commands 349
calibre User Manual, Release 7.19.0
--snb-output-encoding
Specify the character encoding of the output document. The default is utf-8.
TCR Output Options
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--tcr-output-encoding
Specify the character encoding of the output document. The default is utf-8.
TXT Output Options
--force-max-line-length
Force splitting on the max-line-length value when no space is present. Also allows max-line-length to be below the
minimum
--inline-toc
Add Table of Contents to beginning of the book.
--keep-color
Do not remove font color from output. This is only useful when TXT output formatting is set to textile. Textile
is the only formatting that supports setting font color. If this option is not specied font color will not be set and
default to the color displayed by the reader (generally this is black).
--keep-image-references
Do not remove image references within the document. This is only useful when paired with a TXT output formatting
option that is not none because links are always removed with plain text output.
--keep-links
Do not remove links within the document. This is only useful when paired with a TXT output formatting option
that is not none because links are always removed with plain text output.
--max-line-length
The maximum number of characters per line. This splits on the rst space before the specied value. If no space
is found the line will be broken at the space after and will exceed the specied value. Also, there is a minimum of
25 characters. Use 0 to disable line splitting.
--newline, -n
Type of newline to use. Options are ['old_mac', 'system', 'unix', 'windows']. Default is 'system'. Use
'old_mac' for compatibility with Mac OS 9 and earlier. For macOS use 'unix'. 'system' will default to the
newline type used by this OS.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--txt-output-encoding
Specify the character encoding of the output document. The default is utf-8.
--txt-output-formatting
Formatting used within the document. * plain: Plain text * markdown: Markdown formatted text * textile: Textile
formatted text
350 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
TXTZ Output Options
--force-max-line-length
Force splitting on the max-line-length value when no space is present. Also allows max-line-length to be below the
minimum
--inline-toc
Add Table of Contents to beginning of the book.
--keep-color
Do not remove font color from output. This is only useful when TXT output formatting is set to textile. Textile
is the only formatting that supports setting font color. If this option is not specied font color will not be set and
default to the color displayed by the reader (generally this is black).
--keep-image-references
Do not remove image references within the document. This is only useful when paired with a TXT output formatting
option that is not none because links are always removed with plain text output.
--keep-links
Do not remove links within the document. This is only useful when paired with a TXT output formatting option
that is not none because links are always removed with plain text output.
--max-line-length
The maximum number of characters per line. This splits on the rst space before the specied value. If no space
is found the line will be broken at the space after and will exceed the specied value. Also, there is a minimum of
25 characters. Use 0 to disable line splitting.
--newline, -n
Type of newline to use. Options are ['old_mac', 'system', 'unix', 'windows']. Default is 'system'. Use
'old_mac' for compatibility with Mac OS 9 and earlier. For macOS use 'unix'. 'system' will default to the
newline type used by this OS.
--pretty-print
If specied, the output plugin will try to create output that is as human readable as possible. May not have any
eect for some output plugins.
--txt-output-encoding
Specify the character encoding of the output document. The default is utf-8.
--txt-output-formatting
Formatting used within the document. * plain: Plain text * markdown: Markdown formatted text * textile: Textile
formatted text
13.1.8 ebook-edit
ebook-edit [opts] [path_to_ebook] [name_of_file_inside_book ...]
Launch the calibre Edit book tool. You can optionally also specify the names of les inside the book which will be opened
for editing automatically.
Whenever you pass arguments to ebook-edit that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
13.1. Documented commands 351
calibre User Manual, Release 7.19.0
[options]
--detach
Detach from the controlling terminal, if any (Linux only)
--help, -h
show this help message and exit
--select-text
The text to select in the book when it is opened for editing
--version
show program's version number and exit
13.1.9 ebook-meta
ebook-meta ebook_file [options]
Read/Write metadata from/to e-book les.
Supported formats for reading metadata: azw, azw1, azw3, azw4, cb7, cbc, cbr, cbz, chm, docx, epub, fb2, fbz, html,
htmlz, imp, lit, lrf, lrx, mobi, odt, oebzip, opf, pdb, pdf, pml, pmlz, pobi, prc, rar, rb, rtf, snb, tpz, txt, txtz, updb, zip
Supported formats for writing metadata: azw, azw1, azw3, azw4, docx, epub, fb2, fbz, htmlz, lrf, mobi, odt, pdb, pdf,
prc, rtf, tpz, txtz
Dierent le types support dierent kinds of metadata. If you try to set some metadata on a le type that does not support
it, the metadata will be silently ignored.
Whenever you pass arguments to ebook-meta that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
[options]
--author-sort
String to be used when sorting by author. If unspecied, and the author(s) are specied, it will be auto-generated
from the author(s).
--authors, -a
Set the authors. Multiple authors should be separated by the & character. Author names should be in the order
Firstname Lastname.
--book-producer, -k
Set the book producer.
--category
Set the book category.
--comments, -c
Set the e-book description.
--cover
Set the cover to the specied le.
352 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--date, -d
Set the published date.
--from-opf
Read metadata from the specied OPF le and use it to set metadata in the e-book. Metadata specied on the
command line will override metadata read from the OPF le
--get-cover
Get the cover from the e-book and save it at as the specied le.
--help, -h
show this help message and exit
--identifier
Set the identiers for the book, can be specied multiple times. For example: --identifier (page 353)
uri:https://acme.com --identifier (page 353) isbn:12345 To remove an identier, specify no value,
--identifier (page 353) isbn: Note that for EPUB les, an identier marked as the package identier cannot
be removed.
--index, -i
Set the index of the book in this series.
--isbn
Set the ISBN of the book.
--language, -l
Set the language.
--lrf-bookid
Set the BookID in LRF les
--publisher, -p
Set the e-book publisher.
--rating, -r
Set the rating. Should be a number between 1 and 5.
--series, -s
Set the series this e-book belongs to.
--tags
Set the tags for the book. Should be a comma separated list.
--title, -t
Set the title.
--title-sort
The version of the title to be used for sorting. If unspecied, and the title is specied, it will be auto-generated
from the title.
--to-opf
Specify the name of an OPF le. The metadata will be written to the OPF le.
--version
show program's version number and exit
13.1. Documented commands 353
calibre User Manual, Release 7.19.0
13.1.10 ebook-polish
ebook-polish [options] input_file [output_file]
Polishing books is all about putting the shine of perfection onto your carefully crafted e-books.
Polishing tries to minimize the changes to the internal code of your e-book. Unlike conversion, it does not atten CSS,
rename les, change font sizes, adjust margins, etc. Every action performs only the minimum set of changes needed for
the desired eect.
You should use this tool as the last step in your e-book creation process.
Note that polishing only works on les in the AZW3 or EPUB formats.
Whenever you pass arguments to ebook-polish that have spaces in them, enclose the arguments in quotation marks.
For example: “/some path/with spaces”
[options]
--add-soft-hyphens, -H
Add soft hyphens to all words in the book. This allows the book to be rendered better when the text is justied, in
readers that do not support hyphenation.
--compress-images, -i
Losslessly compress images in the book, to reduce the lesize, without aecting image quality.
--cover, -c
Path to a cover image. Changes the cover specied in the e-book. If no cover is present, or the cover is not properly
identied, inserts a new cover.
--download-external-resources, -d
Download external resources such as images, stylesheets, etc. that point to URLs instead of les in the book.
All such resources will be downloaded and added to the book so that the book no longer references any external
resources.
--embed-fonts, -e
Embed all fonts that are referenced in the document and are not already embedded. This will scan your computer
for the fonts, and if they are found, they will be embedded into the document. Please ensure that you have the
proper license for embedding the fonts used in this document.
--help, -h
show this help message and exit
--jacket, -j
Insert a "book jacket" page at the start of the book that contains all the book metadata such as title, tags, authors,
series, comments, etc. Any previous book jacket will be replaced.
--opf, -o
Path to an OPF le. The metadata in the book is updated from the OPF le.
--remove-jacket
Remove a previous inserted book jacket page.
--remove-soft-hyphens
Remove soft hyphens from all text in the book.
354 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--remove-unused-css, -u
Remove all unused CSS rules from stylesheets and <style> tags. Some books created from production templates
can have a large number of extra CSS rules that don't match any actual content. These extra rules can slow down
readers that need to parse them all.
--smarten-punctuation, -p
Convert plain text dashes, ellipsis, quotes, multiple hyphens, etc. into their typographically correct equivalents.
Note that the algorithm can sometimes generate incorrect results, especially when single quotes at the start of
contractions are involved.
--subset-fonts, -f
Subsetting fonts means reducing an embedded font to contain only the characters used from that font in the book.
This greatly reduces the size of the font les (halving the font le sizes is common). For example, if the book uses
a specic font for headers, then subsetting will reduce that font to contain only the characters present in the actual
headers in the book. Or if the book embeds the bold and italic versions of a font, but bold and italic text is relatively
rare, or absent altogether, then the bold and italic fonts can either be reduced to only a few characters or completely
removed. The only downside to subsetting fonts is that if, at a later date you decide to add more text to your books,
the newly added text might not be covered by the subset font.
--upgrade-book, -U
Upgrade the internal structures of the book, if possible. For instance, upgrades EPUB 2 books to EPUB 3 books.
--verbose
Produce more verbose output, useful for debugging.
--version
show program's version number and exit
13.1.11 ebook-viewer
ebook-viewer [options] file
View an e-book.
Whenever you pass arguments to ebook-viewer that have spaces in them, enclose the arguments in quotation marks.
For example: “/some path/with spaces”
[options]
--continue
Continue reading the last opened book
--detach
Detach from the controlling terminal, if any (Linux only)
--force-reload
Force reload of all opened books
--full-screen, --fullscreen, -f
If specied, the E-book viewer window will try to open full screen when started.
--help, -h
show this help message and exit
13.1. Documented commands 355
calibre User Manual, Release 7.19.0
--new-instance
Open a new viewer window even when the option to use only a single viewer window is set
--open-at
The position at which to open the specied book. The position is a location or position you can get by using the Go
to->Location action in the viewer controls. Alternately, you can use the form toc:something and it will open at the
location of the rst Table of Contents entry that contains the string "something". The form toc-href:something
will match the href (internal link destination) of toc nodes. The matching is exact. If you want to match a substring,
use the form toc-href-contains:something. The form ref:something will use Reference mode references. The form
search:something will search for something after opening the book. The form regex:something will search for the
regular expression something after opening the book.
--raise-window
If specied, the E-book viewer window will try to come to the front when started.
--version
show program's version number and exit
13.1.12 fetch-ebook-metadata
fetch-ebook-metadata [options]
Fetch book metadata from online sources. You must specify at least one of title, authors or ISBN.
Whenever you pass arguments to fetch-ebook-metadata that have spaces in them, enclose the arguments in quo-
tation marks. For example: “/some path/with spaces”
[options]
--allowed-plugin, -p
Specify the name of a metadata download plugin to use. By default, all metadata plugins will be used. Can be
specied multiple times for multiple plugins. All plugin names: Google, Google Images, Amazon.com, Edelweiss,
Open Library, Big Book Search
--authors, -a
Book author(s)
--cover, -c
Specify a lename. The cover, if available, will be saved to it. Without this option, no cover will be downloaded.
--help, -h
show this help message and exit
--identifier, -I
Identiers such as ASIN/Goodreads id etc. Can be specied multiple times for multiple identiers. For example:
--identifier (page 356) asin:B0082BAJA0
--isbn, -i
Book ISBN
--opf, -o
Output the metadata in OPF format instead of human readable text.
356 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
--timeout, -d
Timeout in seconds. Default is 30
--title, -t
Book title
--verbose, -v
Print the log to the console (stderr)
--version
show program's version number and exit
13.1.13 lrf2lrs
lrf2lrs book.lrf
Convert an LRF le into an LRS (XML UTF-8 encoded) le
Whenever you pass arguments to lrf2lrs that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
[options]
--dont-output-resources
Do not save embedded image and font les to disk
--help, -h
show this help message and exit
--output, -o
Output LRS le
--verbose
Be more verbose
--version
show program's version number and exit
13.1.14 lrfviewer
lrfviewer [options] book.lrf
Read the LRF e-book book.lrf
Whenever you pass arguments to lrfviewer that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
13.1. Documented commands 357
calibre User Manual, Release 7.19.0
[options]
--disable-hyphenation
Disable hyphenation. Should signicantly speed up rendering.
--help, -h
show this help message and exit
--profile
Prole the LRF renderer
--verbose
Print more information about the rendering process
--version
show program's version number and exit
--visual-debug
Turn on visual aids to debugging the rendering engine
--white-background
By default the background is o white as I nd this easier on the eyes. Use this option to make the background
pure white.
13.1.15 lrs2lrf
lrs2lrf [options] file.lrs
Compile an LRS le into an LRF le.
Whenever you pass arguments to lrs2lrf that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
[options]
--help, -h
show this help message and exit
--lrs
Convert LRS to LRS, useful for debugging.
--output, -o
Path to output le
--verbose
Verbose processing
--version
show program's version number and exit
358 Chapter 13. Command Line Interface
calibre User Manual, Release 7.19.0
13.1.16 web2disk
web2disk URL
Where URL is for example https://google.com
Whenever you pass arguments to web2disk that have spaces in them, enclose the arguments in quotation marks. For
example: “/some path/with spaces”
[options]
--base-dir, -d
Base folder into which URL is saved. Default is .
--delay
Minimum interval in seconds between consecutive fetches. Default is 0 s
--dont-download-stylesheets
Do not download CSS stylesheets.
--encoding
The character encoding for the websites you are trying to download. The default is to try and guess the encoding.
--filter-regexp
Any link that matches this regular expression will be ignored. This option can be specied multiple times, in which
case as long as any regexp matches a link, it will be ignored. By default, no links are ignored. If both lter regexp
and match regexp are specied, then lter regexp is applied rst.
--help
,
-h
show this help message and exit
--match-regexp
Only links that match this regular expression will be followed. This option can be specied multiple times, in which
case as long as a link matches any one regexp, it will be followed. By default all links are followed.
--max-files, -n
The maximum number of les to download. This only applies to les from <a href> tags. Default is
9223372036854775807
--max-recursions, -r
Maximum number of levels to recurse i.e. depth of links to follow. Default 1
--timeout, -t
Timeout in seconds to wait for a response from the server. Default: 10.0 s
--verbose
Show detailed output information. Useful for debugging
--version
show program's version number and exit
13.1. Documented commands 359
calibre User Manual, Release 7.19.0
13.2 Undocumented commands
ebook-device
markdown-calibre
You can see usage for undocumented commands by executing them without arguments in a terminal.
360 Chapter 13. Command Line Interface
CHAPTER
FOURTEEN
SETTING UP A CALIBRE DEVELOPMENT ENVIRONMENT
calibre is completely open source, licensed under the GNU GPL v3
114
. This means that you are free to download and
modify the program to your heart’s content. In this section, you will learn how to get a calibre development environment
set up on the operating system of your choice. calibre is written primarily in Python
115
with some C/C++ code for speed
and system interfacing. Note that calibre requires at least Python 3.8.
Contents
Design philosophy (page 362)
Code layout (page 362)
Getting the code (page 363)
Submitting your changes to be included (page 363)
Windows development environment (page 364)
macOS development environment (page 365)
Linux development environment (page 365)
Having separate “normal” and “development” calibre installs on the same computer (page 366)
Debugging tips (page 367)
Using print statements (page 367)
Using an interactive Python interpreter (page 367)
Using the Python debugger as a remote debugger (page 367)
Using the debugger in your favorite Python IDE (page 368)
Executing arbitrary scripts in the calibre Python environment (page 368)
Using calibre in your projects (page 369)
Binary install of calibre (page 369)
Source install on Linux (page 369)
API documentation for various parts of calibre (page 369)
114
https://www.gnu.org/licenses/gpl.html
115
https://www.python.org
361
calibre User Manual, Release 7.19.0
14.1 Design philosophy
calibre has its roots in the Unix world, which means that its design is highly modular. The modules interact with each other
via well dened interfaces. This makes adding new features and xing bugs in calibre very easy, resulting in a frenetic
pace of development. Because of its roots, calibre has a comprehensive command line interface for all its functions,
documented in Command Line Interface (page 303).
The modular design of calibre is expressed via Plugins. There is a tutorial (page 257) on writing calibre plugins. For
example, adding support for a new device to calibre typically involves writing less than a 100 lines of code in the form
of a device driver plugin. You can browse the built-in drivers
116
. Similarly, adding support for new conversion formats
involves writing input/output format plugins. Another example of the modular design is the recipe system (page 31) for
fetching news. For more examples of plugins designed to add features to calibre, see the Index of plugins
117
.
14.1.1 Code layout
All the calibre Python code is in the calibre package. This package contains the following main sub-packages
devices - All the device drivers. Just look through some of the built-in drivers to get an idea for how they work.
For details, see: devices.interface which denes the interface supported by device drivers and
devices.usbms which denes a generic driver that connects to a USBMS device. All USBMS based
drivers in calibre inherit from it.
e-books - All the e-book conversion/metadata code. A good starting point is calibre.ebooks.
conversion.cli which is the module powering the ebook-convert command. The conversion process is
controlled via conversion.plumber. The format independent code is all in ebooks.oeb and the format
dependent code is in ebooks.format_name.
Metadata reading, writing, and downloading is all in ebooks.metadata
Conversion happens in a pipeline, for the structure of the pipeline, see Introduction (page 61). The pipeline
consists of an input plugin, various transforms and an output plugin. The code that constructs and drives the
pipeline is in plumber.py. The pipeline works on a representation of an e-book that is like an unzipped
epub, with manifest, spine, toc, guide, html content, etc. The class that manages this representation is OEB-
Book in ebooks.oeb.base. The various transformations that are applied to the book during conversions
live in oeb/transforms/*.py. And the input and output plugins live in conversion/plugins/
*.py.
E-book editing happens using a dierent container object. It is documented in API documentation for the
e-book editing tools (page 379).
db - The database back-end. See API documentation for the database interface (page 369) for the interface to the
calibre library.
Content server: srv is the calibre Content server.
gui2 - The Graphical User Interface. GUI initialization happens in gui2.main and gui2.ui. The e-book-
viewer is in gui2.viewer. The e-book editor is in gui2.tweak_book.
If you want to locate the entry points for all the various calibre executables, look at the entry_points structure in
linux.py
118
.
If you need help understanding the code, post in the development forum
119
and you will most likely get help from one of
calibre’s many developers.
116
https://github.com/kovidgoyal/calibre/tree/master/src/calibre/devices
117
https://www.mobileread.com/forums/showthread.php?p=1362767#post1362767
118
https://github.com/kovidgoyal/calibre/blob/master/src/calibre/linux.py
119
https://www.mobileread.com/forums/forumdisplay.php?f=240
362 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
14.2 Getting the code
You can get the calibre source code in two ways, using a version control system or directly downloading a tarball
120
.
calibre uses Git
121
, a distributed version control system. Git is available on all the platforms calibre supports. After
installing Git, you can get the calibre source code with the command:
git clone https://github.com/kovidgoyal/calibre.git
On Windows you will need the complete path name, that will be something like C:\Program Files\Git\git.
exe.
calibre is a very large project with a very long source control history, so the above can take a while (10 mins to an hour
depending on your internet speed).
If you want to get the code faster, the source code for the latest release is always available as an archive
122
.
To update a branch to the latest code, use the command:
git pull --no-edit
You can also browse the code at GitHub
123
.
14.2.1 Submitting your changes to be included
If you only plan to make a few small changes, you can make your changes and create a “merge directive” which you can
then attach to a ticket in the calibre bug tracker
124
. To do this, make your changes, then run:
git commit -am "Comment describing your changes"
git format-patch origin/master --stdout > my-changes
This will create a my-changes le in the current folder, simply attach that to a ticket on the calibre bug tracker
125
.
Note that this will include all the commits you have made. If you only want to send some commits, you have to change
origin/master above. To send only the last commit, use:
git format-patch HEAD~1 --stdout > my-changes
To send the last n commits, replace 1 with n, for example, for the last 3 commits:
git format-patch HEAD~3 --stdout > my-changes
Be careful to not include merges when using HEAD~n.
If you plan to do a lot of development on calibre, then the best method is to create a GitHub
126
account. Below is a basic
guide to setting up your own fork of calibre in a way that will allow you to submit pull requests for inclusion into the main
calibre repository:
Setup git on your machine as described in this article: Setup Git
127
Setup ssh keys for authentication to GitHub, as described here: Generating SSH keys
128
120
https://calibre-ebook.com/dist/src
121
https://www.git-scm.com/
122
https://calibre-ebook.com/dist/src
123
https://github.com/kovidgoyal/calibre
124
https://bugs.launchpad.net/calibre
125
https://bugs.launchpad.net/calibre
126
https://github.com
127
https://help.github.com/articles/set-up-git
128
https://help.github.com/articles/generating-ssh-keys
14.2. Getting the code 363
calibre User Manual, Release 7.19.0
Go to https://github.com/kovidgoyal/calibre and click the Fork button.
In a Terminal do:
git clone git@github.com:<username>/calibre.git
git remote add upstream https://github.com/kovidgoyal/calibre.git
Replace <username> above with your GitHub username. That will get your fork checked out locally.
You can make changes and commit them whenever you like. When you are ready to have your work merged, do a:
git push
and go to https://github.com/<username>/calibre and click the Pull Request button to generate a
pull request that can be merged.
You can update your local copy with code from the main repo at any time by doing:
git pull upstream
You should also keep an eye on the calibre development forum
129
. Before making major changes, you should discuss
them in the forum or contact Kovid directly (his email address is all over the source code).
14.3 Windows development environment
® Note
You must also get the calibre source code separately as described above.
Install calibre normally, using the Windows installer
130
. Then open a Command Prompt and change to the previously
checked out calibre code folder. For example:
cd C:\Users\kovid\work\calibre
calibre is the folder that contains the src and resources sub-folders.
The next step is to set the environment variable CALIBRE_DEVELOP_FROM to the absolute path of the src folder. So,
following the example above, it would be C:\Users\kovid\work\calibre\src. Here is a short guide
131
to
setting environment variables on Windows.
Once you have set the environment variable, open a new command prompt and check that it was correctly set by using
the command:
echo %CALIBRE_DEVELOP_FROM%
Setting this environment variable means that calibre will now load all its Python code from the specied location.
That’s it! You are now ready to start hacking on the calibre code. For example, open the le src\calibre\
__init__.py in your favorite editor and add the line:
print("Hello, world!")
129
https://www.mobileread.com/forums/forumdisplay.php?f=240
130
https://calibre-ebook.com/download_windows
131
https://docs.python.org/using/windows.html#excursus-setting-environment-variables
364 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
near the top of the le. Now run the command calibredb. The very rst line of output should be Hello, world!.
You can also setup a calibre development environment inside the free Microsoft Visual Studio, if you like, following the
instructions here
132
.
14.4 macOS development environment
® Note
You must also get the calibre source code separately as described above.
Install calibre normally using the provided .dmg
133
. Then open a Terminal and change to the previously checked out
calibre code folder, for example:
cd /Users/kovid/work/calibre
calibre is the folder that contains the src and resources sub-folders. The calibre command line tools are found inside the
calibre app bundle, in /Applications/calibre.app/Contents/MacOS you should add this folder to your
PATH environment variable, if you want to run the command line tools easily.
The next step is to create a bash script that will set the environment variable CALIBRE_DEVELOP_FROM to the absolute
path of the src folder when running calibre in debug mode.
Create a plain text le:
#!/bin/sh
export CALIBRE_DEVELOP_FROM="/Users/kovid/work/calibre/src"
calibre-debug -g
Save this le as /usr/local/bin/calibre-develop, then set its permissions so that it can be executed:
chmod +x /usr/local/bin/calibre-develop
Once you have done this, run:
calibre-develop
You should see some diagnostic information in the Terminal window as calibre starts up, and you should see an asterisk
after the version number in the GUI window, indicating that you are running from source.
14.5 Linux development environment
® Note
You must also get the calibre source code separately as described above.
calibre is primarily developed on Linux. You have two choices in setting up the development environment. You can
install the calibre binary as normal and use that as a runtime environment to do your development. This approach is
132
https://www.mobileread.com/forums/showthread.php?t=251201
133
https://calibre-ebook.com/download_osx
14.4. macOS development environment 365
calibre User Manual, Release 7.19.0
similar to that used in Windows and macOS. Alternatively, you can install calibre from source. Instructions for setting
up a development environment from source are in the INSTALL le in the source tree. Here we will address using the
binary as a runtime, which is the recommended method.
Install calibre using the binary installer
134
. Then open a terminal and change to the previously checked out calibre code
folder, for example:
cd /home/kovid/work/calibre
calibre is the folder that contains the src and resources sub-folders.
The next step is to set the environment variable CALIBRE_DEVELOP_FROM to the absolute path of the src folder. So,
following the example above, it would be /home/kovid/work/calibre/src. How to set environment variables
depends on your Linux distribution and what shell you are using.
® Note
It is recommended to use the binary installer provided from upstream. Should you insist on using a package provided
by your distribution, use the CALIBRE_PYTHON_PATH and CALIBRE_RESOURCES_PATH variables instead.
Once you have set the environment variable, open a new terminal and check that it was correctly set by using the command:
echo $CALIBRE_DEVELOP_FROM
Setting this environment variable means that calibre will now load all its Python code from the specied location.
That’s it! You are now ready to start hacking on the calibre code. For example, open the le src/calibre/
__init__.py in your favorite editor and add the line:
print("Hello, world!")
near the top of the le. Now run the command calibredb. The very rst line of output should be Hello, world!.
14.6 Having separate “normal” and “development” calibre installs on
the same computer
The calibre source tree is very stable and rarely breaks, but if you feel the need to run from source on a separate test
library and run the released calibre version with your everyday library, you can achieve this easily using .bat les or shell
scripts to launch calibre. The example below shows how to do this on Windows using .bat les (the instructions for other
platforms are the same, just use a shell script instead of a .bat le)
To launch the release version of calibre with your everyday library:
calibre-normal.bat:
calibre.exe "--with-library=C:\path\to\everyday\library folder"
calibre-dev.bat:
set CALIBRE_DEVELOP_FROM=C:\path\to\calibre\checkout\src
calibre.exe "--with-library=C:\path\to\test\library folder"
134
https://calibre-ebook.com/download_linux
366 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
14.7 Debugging tips
Python is a dynamically typed language with excellent facilities for introspection. Kovid wrote the core calibre code
without once using a debugger. There are many strategies to debug calibre code:
14.7.1 Using print statements
This is Kovid’s favorite way to debug. Simply insert print statements at points of interest and run your program in the
terminal. For example, you can start the GUI from the terminal as:
calibre-debug -g
Similarly, you can start the E-book viewer as:
calibre-debug -w /path/to/file/to/be/viewed
The e-book editor can be started as:
calibre-debug --edit-book /path/to/be/edited
14.7.2 Using an interactive Python interpreter
You can insert the following two lines of code to start an interactive Python session at that point:
from calibre import ipython
ipython(locals())
When running from the command line, this will start an interactive Python interpreter with access to all locally dened
variables (variables in the local scope). The interactive prompt even has Tab completion for object properties and you
can use the various Python facilities for introspection, such as dir(), type(), repr(), etc.
14.7.3 Using the Python debugger as a remote debugger
You can use the builtin Python debugger (pdb) as a remote debugger from the command line. First, start the remote
debugger at the point in the calibre code you are interested in, like this:
from calibre.rpdb import set_trace
set_trace()
Then run calibre, either as normal, or using one of the calibre-debug commands described in the previous section. Once
the above point in the code is reached, calibre will freeze, waiting for the debugger to connect.
Now open a terminal or command prompt and use the following command to start the debugging session:
calibre-debug -c "from calibre.rpdb import cli; cli()"
You can read about how to use the Python debugger in the Python stdlib docs for the pdb module
135
.
135
https://docs.python.org/library/pdb.html#debugger-commands
14.7. Debugging tips 367
calibre User Manual, Release 7.19.0
® Note
By default, the remote debugger will try to connect on port 4444. You can change it, by passing the port parameter to
both the set_trace() and the cli() functions above, like this: set_trace(port=1234) and cli(port=1234).
® Note
The Python debugger cannot handle multiple threads, so you have to call set_trace once per thread, each time with a
dierent port number.
14.7.4 Using the debugger in your favorite Python IDE
It is possible to use the builtin debugger in your favorite Python IDE, if it supports remote debugging. The rst step
is to add the calibre src checkout to the PYTHONPATH in your IDE. In other words, the folder you set as CALI-
BRE_DEVELOP_FROM above, must also be in the PYTHONPATH of your IDE.
Then place the IDE’s remote debugger module into the src sub-folder of the calibre source code checkout. Add whatever
code is needed to launch the remote debugger to calibre at the point of interest, for example in the main function. Then
run calibre as normal. Your IDE should now be able to connect to the remote debugger running inside calibre.
14.7.5 Executing arbitrary scripts in the calibre Python environment
The calibre-debug command provides a couple of handy switches to execute your own code, with access to the
calibre modules:
calibre-debug -c "some Python code"
is great for testing a little snippet of code on the command line. It works in the same way as the -c switch to the Python
interpreter:
calibre-debug myscript.py
can be used to execute your own Python script. It works in the same way as passing the script to the Python interpreter,
except that the calibre environment is fully initialized, so you can use all the calibre code in your script. To use command
line arguments with your script, use the form:
calibre-debug myscript.py -- --option1 arg1
The
--
causes all subsequent arguments to be passed to your script.
368 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
14.8 Using calibre in your projects
It is possible to directly use calibre functions/code in your Python project. Two ways exist to do this:
14.8.1 Binary install of calibre
If you have a binary install of calibre, you can use the Python interpreter bundled with calibre, like this:
calibre-debug /path/to/your/python/script.py -- arguments to your script
14.8.2 Source install on Linux
In addition to using the above technique, if you do a source install on Linux, you can also directly import calibre, as
follows:
import init_calibre
import calibre
print(calibre.__version__)
It is essential that you import the init_calibre module before any other calibre modules/packages as it sets up the interpreter
to run calibre code.
14.9 API documentation for various parts of calibre
14.9.1 API documentation for the database interface
This API is thread safe (it uses a multiple reader, single writer locking scheme). You can access this API like this:
from calibre.library import db
db = db('Path to calibre library folder').new_api
If you are in a calibre plugin that is part of the main calibre GUI, you get access to it like this instead:
db = self.gui.current_db.new_api
class calibre.db.cache.Cache(backend, library_database_instance=None)
An in-memory cache of the metadata.db le from a calibre library. This class also serves as a threadsafe API for
accessing the database. The in-memory cache is maintained in normal form for maximum performance.
SQLITE is simply used as a way to read and write from metadata.db robustly. All table read-
ing/sorting/searching/caching logic is re-implemented. This was necessary for maximum performance and exi-
bility.
class EventType(value, names=<not given>, *values, module=None, qualname=None, type=None,
start=1, boundary=None)
book_created = 4
When a new book record is created in the database, with the book id as the only argument
14.8. Using calibre in your projects 369
calibre User Manual, Release 7.19.0
book_edited = 8
When a book format is edited, with arguments: (book_id, fmt)
books_removed = 5
When books are removed from the database with the list of book ids as the only argument
format_added = 2
When a format is added to a book, with arguments: (book_id, format)
formats_removed = 3
When formats are removed from a book, with arguments: (mapping of book id to set of formats removed
from the book)
indexing_progress_changed = 9
When the indexing progress changes
items_removed = 7
When items such as tags or authors are removed from some books. Arguments: (eld_name, aected
book ids, ids of removed items)
items_renamed = 6
When items such as tags or authors are renamed in some or all books. Arguments: (eld_name, aected
book ids, map of old item id to new item id)
metadata_changed = 1
When some metadata is changed for some books, with arguments: (name of changed eld, set of aected
book ids)
add_books(books, add_duplicates=True, apply_import_tags=True, preserve_uuid=False, run_hooks=True,
dbapi=None)
Add the specied books to the library. Books should be an iterable of 2-tuples, each 2-tuple of the form
(mi, format_map) where mi is a Metadata object and format_map is a dictionary of the form {fmt:
path_or_stream}, for example: {'EPUB': '/path/to/file.epub'}.
Returns a pair of lists: ids, duplicates. ids contains the book ids for all newly created books in the
database. duplicates contains the (mi, format_map) for all books that already exist in the database
as per the simple duplicate detection heuristic used by has_book() (page 375).
add_custom_book_data(name, val_map, delete_rst=False)
Add data for name where val_map is a map of book_ids to values. If delete_rst is True, all previously stored
data for name will be removed.
add_extra_files(book_id, map_of_relpath_to_stream_or_path, replace=True, auto_rename=False)
Add extra data les
add_format(book_id, fmt, stream_or_path, replace=True, run_hooks=True, dbapi=None)
Add a format to the specied book. Return True if the format was added successfully.
Parameters
replace If True replace existing format, otherwise if the format already exists, return
False.
run_hooks If True, le type plugins are run on the format before and after being added.
dbapi Internal use only.
370 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
add_listener(event_callback_function, check_already_added=False)
Register a callback function that will be called after certain actions are taken on this database. The function
must take three arguments: (EventType (page 369), library_id, event_type_specic_data)
add_notes_resource(path_or_stream_or_data, name: str, mtime: oat = None) int
Add the specied resource so it can be referenced by notes and return its content hash
all_annotation_types()
Return a tuple of all annotation types in the database.
all_annotation_users()
Return a tuple of all (user_type, user name) that have annotations.
all_annotations(restrict_to_user=None, limit=None, annotation_type=None, ignore_removed=False,
restrict_to_book_ids=None)
Return a tuple of all annotations matching the specied criteria. ignore_removed controls whether removed
(deleted) annotations are also returned. Removed annotations are just a skeleton used for merging of anno-
tations.
all_annotations_for_book(book_id)
Return a tuple containing all annotations for the specied book_id as a dict with keys: format, user_type, user,
annotation. Here, annotation is the annotation data.
all_book_ids(type=<class 'frozenset'>)
Frozen set of all known book ids.
all_field_for(eld, book_ids, default_value=None)
Same as eld_for, except that it operates on multiple books at once
all_field_ids(name)
Frozen set of ids for all values in the eld name.
all_field_names(eld)
Frozen set of all elds names (should only be used for many-one and many-many elds)
annotation_count_for_book(book_id)
Return the number of annotations for the specied book available in the database.
annotations_map_for_book(book_id, fmt, user_type='local', user='viewer')
Return a map of annotation type -> annotation data for the specied book_id, format, user and user_type.
author_data(author_ids=None)
Return author data as a dictionary with keys: name, sort, link
If no authors with the specied ids are found an empty dictionary is returned. If author_ids is None, data for
all authors is returned.
author_sort_from_authors(authors, key_func=<function
make_change_case_func.<locals>.change_case>)
Given a list of authors, return the author_sort string for the authors, preferring the author sort associated with
the author over the computed string.
books_for_field(name, item_id)
Return all the books associated with the item identied by item_id, where the item belongs to the eld
name.
Returned value is a set of book ids, or the empty set if the item or the eld does not exist.
14.9. API documentation for various parts of calibre 371
calibre User Manual, Release 7.19.0
books_in_virtual_library(vl, search_restriction=None, virtual_elds=None)
Return the set of books in the specied virtual library
compress_covers(book_ids, jpeg_quality=100, progress_callback=None)
Compress the cover images for the specied books. A compression quality of 100 will perform lossless
compression, otherwise lossy compression.
The progress callback will be called with the book_id and the old and new sizes for each book that has been
processed. If an error occurs, the new size will be a string with the error details.
copy_cover_to(book_id, dest, use_hardlink=False, report_le_size=None)
Copy the cover to the le like object dest. Returns False if no cover exists or dest is the same le as the
current cover. dest can also be a path in which case the cover is copied to it if and only if the path is dierent
from the current path (taking case sensitivity into account).
copy_format_to(book_id, fmt, dest, use_hardlink=False, report_le_size=None)
Copy the format fmt to the le like object dest. If the specied format does not exist, raises NoSuch-
Format error. dest can also be a path (to a le), in which case the format is copied to it, i the path is
dierent from the current path (taking case sensitivity into account).
cover(book_id, as_le=False, as_image=False, as_path=False, as_pixmap=False)
Return the cover image or None. By default, returns the cover as a bytestring.
WARNING: Using as_path will copy the cover to a temp le and return the path to the temp le. You should
delete the temp le when you are done with it.
Parameters
as_file If True return the image as an open le object (a SpooledTemporaryFile)
as_image If True return the image as a QImage object
as_pixmap If True return the image as a QPixmap object
as_path If True return the image as a path pointing to a temporary le
data_for_find_identical_books()
Return data that can be used to implement find_identical_books() (page 373) in a worker process
without access to the db. See db.utils for an implementation.
data_for_has_book()
Return data suitable for use in has_book() (page 375). This can be used for an implementation of
has_book() (page 375) in a worker process without access to the db.
delete_annotations(annot_ids)
Delete annotations with the specied ids.
delete_custom_book_data(name, book_ids=())
Delete data for name. By default deletes all data, if you only want to delete data for some book ids, pass in a
list of book ids.
delete_trash_entry(book_id, category)
Delete an entry from the trash. Here category is ‘b’ for books and ‘f’ for formats.
embed_metadata(book_ids, only_fmts=None, report_error=None, report_progress=None)
Update metadata in all formats of the specied book_ids to current metadata in the database.
expire_old_trash()
Expire entries from the trash that are too old
372 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
export_note(eld, item_id) str
Export the note as a single HTML document with embedded images as data: URLs
fast_field_for(eld_obj, book_id, default_value=None)
Same as eld_for, except that it avoids the extra lookup to get the eld object
field_for(name, book_id, default_value=None)
Return the value of the eld name for the book identied by book_id. If no such book exists or it has no
dened value for the eld name or no such eld exists, then default_value is returned.
default_value is not used for title, title_sort, authors, author_sort and series_index. This is because
these always have values in the db. default_value is used for all custom columns.
The returned value for is_multiple elds are always tuples, even when no values are found (in other words,
default_value is ignored). The exception is identiers for which the returned value is always a dictionary. The
returned tuples are always in link order, that is, the order in which they were created.
field_ids_for(name, book_id)
Return the ids (as a tuple) for the values that the eld name has on the book identied by book_id. If there
are no values, or no such book, or no such eld, an empty tuple is returned.
field_supports_notes(eld=None) bool
Return True i the specied eld supports notes. If eld is None return frozenset of all elds that support
notes.
find_identical_books(mi, search_restriction='', book_ids=None)
Finds books that have a superset of the authors in mi and the same title (title is fuzzy matched). See also
data_for_find_identical_books() (page 372).
format(book_id, fmt, as_le=False, as_path=False, preserve_lename=False)
Return the e-book format as a bytestring or None if the format doesn’t exist, or we don’t have permission to
write to the e-book le.
Parameters
as_file If True the e-book format is returned as a le object. Note that the le object
is a SpooledTemporaryFile, so if what you want to do is copy the format to another le, use
copy_format_to() (page 372) instead for performance.
as_path Copies the format le to a temp le and returns the path to the temp le
preserve_filename If True and returning a path the lename is the same as that used
in the library. Note that using this means that repeated calls yield the same temp le (which
is re-created each time)
format_abspath(book_id, fmt)
Return absolute path to the e-book le of format format. You should almost never use this, as it breaks the
threadsafe promise of this API. Instead use, copy_format_to() (page 372).
Currently used only in calibredb list, the viewer, edit book, compare_format to original format, open with,
bulk metadata edit and the catalogs (via get_data_as_dict()).
Apart from the viewer, open with and edit book, I don’t believe any of the others do any le write I/O with
the results of this call.
format_hash(book_id, fmt)
Return the hash of the specied format for the specied book. The kind of hash is backend dependent, but
is usually SHA-256.
14.9. API documentation for various parts of calibre 373
calibre User Manual, Release 7.19.0
format_metadata(book_id, fmt, allow_cache=True, update_db=False)
Return the path, size and mtime for the specied format for the specied book. You should not use path
unless you absolutely have to, since accessing it directly breaks the threadsafe guarantees of this API. Instead
use the copy_format_to() (page 372) method.
Parameters
allow_cache If True cached values are used, otherwise a slow lesystem access is
done. The cache values could be out of date if access was performed to the lesystem outside
of this API.
update_db If True The max_size eld of the database is updated for this book.
formats(book_id, verify_formats=True)
Return tuple of all formats for the specied book. If verify_formats is True, veries that the les exist on
disk.
get_all_items_that_have_notes(eld_name=None) set[int] | dict[str, set[int]]
Return all item_ids for items that have notes in the specied eld or all elds if eld_name is None
get_all_link_maps_for_book(book_id)
Returns all links for all elds referenced by book identied by book_id. If book_id doesn’t exist then the
method returns {}.
Example: Assume author A has link X, author B has link Y, tag S has link F, and tag T has link G. If book 1
has author A and tag T, this method returns {‘authors’:{‘A’:’X’}, ‘tags’:{‘T’, ‘G’}}. If book 2’s author is neither
A nor B and has no tags, this method returns {}.
Parameters
book_id the book id in question.
Returns
{eld: {eld_value, link_value}, for all elds with a eld_value having a non-empty link
value for that book
get_categories(sort='name', book_ids=None, already_xed=None, rst_letter_sort=False)
Used internally to implement the Tag Browser
get_custom_book_data(name, book_ids=(), default=None)
Get data for name. By default returns data for all book_ids, pass in a list of book ids if you only want some
data. Returns a map of book_id to values. If a particular value could not be decoded, uses default for it.
get_id_map(eld)
Return a mapping of id numbers to values for the specied eld. The eld must be a many-one or many-many
eld, otherwise a ValueError is raised.
get_ids_for_custom_book_data(name)
Return the set of book ids for which name has data.
get_item_id(eld, item_name, case_sensitive=False)
Return the item id for item_name or None if not found. This function is very slow if doing lookups for multiple
names use either get_item_ids() or get_item_name_map(). Similarly, case sensitive lookups are faster than
case insensitive ones.
get_item_ids(eld, item_names, case_sensitive=False)
Return a dict mapping item_name to the item id or None
374 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
get_item_name(eld, item_id)
Return the item name for the item specied by item_id in the specied eld. See also get_id_map()
(page 374).
get_item_name_map(eld, normalize_func=None)
Return mapping of item values to ids
get_link_map(for_eld)
Return a dictionary of links for the supplied eld.
Parameters
for_field the lookup name of the eld for which the link map is desired
Returns
{eld_value:link_value, …} for non-empty links
get_metadata(book_id, get_cover=False, get_user_categories=True, cover_as_data=False)
Return metadata for the book identied by book_id as a calibre.ebooks.metadata.book.base.
Metadata (page 211) object. Note that the list of formats is not veried. If get_cover is True, the cover is
returned, either a path to temp le as mi.cover or if cover_as_data is True then as mi.cover_data.
get_next_series_num_for(series, eld='series', current_indices=False)
Return the next series index for the specied series, taking into account the various preferences that control
next series number generation.
Parameters
field The series-like eld (defaults to the builtin series column)
current_indices If True, returns a mapping of book_id to current series_index value
instead.
get_notes_resource(resource_hash) dict | None
Return a dict containing the resource data and name or None if no resource with the specied hash is found
get_proxy_metadata(book_id)
Like get_metadata() (page 375) except that it returns a ProxyMetadata object that only reads values
from the database on demand. This is much faster than get_metadata when only a small number of elds need
to be accessed from the returned metadata object.
get_usage_count_by_id(eld)
Return a mapping of id to usage count for all values of the specied eld, which must be a many-one or
many-many eld.
has_book(mi)
Return True i the database contains an entry with the same title as the passed in Metadata object. The
comparison is case-insensitive. See also data_for_has_book() (page 372).
has_format(book_id, fmt)
Return True i the format exists on disk
has_id(book_id)
Return True i the specied book_id exists in the db
import_note(eld, item_id, path_to_html_le, path_is_data=False)
Import a previously exported note or an arbitrary HTML le as the note for the specied item
init()
Initialize this cache with data from the backend.
14.9. API documentation for various parts of calibre 375
calibre User Manual, Release 7.19.0
items_with_notes_in_book(book_id: int) dict[str, dict[int, str]]
Return a dict of eld to items that have associated notes for that eld for the specied book
link_for(eld, item_id)
Return the link, if any, for the specied item or None if no link is found
list_extra_files(book_id, use_cache=False, pattern='') Tuple[ExtraFile, ...]
Get information about extra les in the book’s directory.
Parameters
book_id the database book id for the book
pattern the pattern of lenames to search for. Empty pattern matches all extra les.
Patterns must use / as separator. Use the DATA_FILE_PATTERN constant to match les
inside the data directory.
Returns
A tuple of all extra les matching the specied pattern. Each element of the tuple is Ex-
traFile(relpath, le_path, stat_result). Where relpath is the relative path of the le to the book
directory using / as a separator. stat_result is the result of calling os.stat() on the le.
merge_annotations_for_book(book_id, fmt, annots_list, user_type='local', user='viewer')
Merge the specied annotations into the existing annotations for book_id, fm, user_type, and user.
merge_extra_files(dest_id, src_ids, replace=False)
Merge the extra les from src_ids into dest_id. Conicting les are auto-renamed unless replace=True in
which case they are replaced.
move_book_from_trash(book_id)
Undelete a book from the trash directory
move_format_from_trash(book_id, fmt)
Undelete a format from the trash directory
multisort(elds, ids_to_sort=None, virtual_elds=None)
Return a list of sorted book ids. If ids_to_sort is None, all book ids are returned.
elds must be a list of 2-tuples of the form (eld_name, ascending=True or False). The most signicant eld
is the rst 2-tuple.
notes_data_for(eld, item_id) str
Return all notes data as a dict or None if note does not exist
notes_for(eld, item_id) str
Return the notes document or an empty string if not found
notes_resources_used_by(eld, item_id)
Return the set of resource hashes of all resources used by the note for the specied item
pref(name, default=None, namespace=None)
Return the value for the specied preference or the value specied as default if the preference is not set.
read_backup(book_id)
Return the OPF metadata backup for the book as a bytestring or None if no such backup exists.
remove_books(book_ids, permanent=False)
Remove the books specied by the book_ids from the database and delete their format les. If permanent
is False, then the format les are placed in the per-library trash directory.
376 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
remove_formats(formats_map, db_only=False)
Remove the specied formats from the specied books.
Parameters
formats_map A mapping of book_id to a list of formats to be removed from the book.
db_only If True, only remove the record for the format from the db, do not delete the
actual format le from the lesystem.
Returns
A map of book id to set of formats actually deleted from the lesystem for that book
remove_items(eld, item_ids, restrict_to_book_ids=None)
Delete all items in the specied eld with the specied ids. Returns the set of aected book ids. re-
strict_to_book_ids is an optional set of books ids. If specied the items will only be removed from
those books.
rename_extra_files(book_id, map_of_relpath_to_new_relpath, replace=False)
Rename extra data les
rename_items(eld, item_id_to_new_name_map, change_index=True, restrict_to_book_ids=None)
Rename items from a many-one or many-many eld such as tags or series.
Parameters
change_index When renaming in a series-like eld also change the series_index values.
restrict_to_book_ids An optional set of book ids for which the rename is to be
performed, defaults to all books.
restore_book(book_id, mi, last_modied, path, formats, annotations=())
Restore the book entry in the database for a book that already exists on the lesystem
restore_original_format(book_id, original_fmt)
Restore the specied format from the previously saved ORIGINAL_FORMAT, if any. Return True on
success. The ORIGINAL_FORMAT is deleted after a successful restore.
property safe_read_lock
A safe read lock is a lock that does nothing if the thread already has a write lock, otherwise it acquires a read
lock. This is necessary to prevent DowngradeLockErrors, which can happen when updating the search cache
in the presence of composite columns. Updating the search cache holds an exclusive lock, but searching a
composite column involves reading eld values via ProxyMetadata which tries to get a shared lock. There
may be other scenarios that trigger this as well.
This property returns a new lock object on every access. This lock object is not recursive (for performance)
and must only be used in a with statement as with cache.safe_read_lock: otherwise bad things
will happen.
save_original_format(book_id, fmt)
Save a copy of the specied format as ORIGINAL_FORMAT, overwriting any existing ORIGI-
NAL_FORMAT.
search(query, restriction='', virtual_elds=None, book_ids=None)
Search the database for the specied query, returning a set of matched book ids.
Parameters
restriction A restriction that is ANDed to the specied query. Note that restrictions
are cached, therefore the search for a AND b will be slower than a with restriction b.
14.9. API documentation for various parts of calibre 377
calibre User Manual, Release 7.19.0
virtual_fields Used internally (virtual elds such as on_device to search over).
book_ids If not None, a set of book ids for which books will be searched instead of
searching all books.
search_annotations(fts_engine_query, use_stemming=True, highlight_start=None, highlight_end=None,
snippet_size=None, annotation_type=None, restrict_to_book_ids=None,
restrict_to_user=None, ignore_removed=False)
Return of a tuple of annotations matching the specied Full-text query.
search_notes(fts_engine_query='', use_stemming=True, highlight_start=None, highlight_end=None,
snippet_size=None, restrict_to_elds=(), return_text=True, result_type=<class 'tuple'>,
process_each_result=None, limit=None)
Search the text of notes using an FTS index. If the query is empty return all notes.
set_annotations_for_book(book_id, fmt, annots_list, user_type='local', user='viewer')
Set all annotations for the specied book_id, fmt, user_type and user.
set_conversion_options(options, fmt='PIPE')
options must be a map of the form {book_id:conversion_options}
set_cover(book_id_data_map)
Set the cover for this book. The data can be either a QImage, QPixmap, le object or bytestring. It can also
be None, in which case any existing cover is removed.
set_field(name, book_id_to_val_map, allow_case_change=True, do_path_update=True)
Set the values of the eld specied by name. Returns the set of all book ids that were aected by the change.
Parameters
book_id_to_val_map Mapping of book_ids to values that should be applied.
allow_case_change If True, the case of many-one or many-many elds will be
changed. For example, if a book has the tag tag1 and you set the tag for another book
to Tag1 then the both books will have the tag Tag1 if allow_case_change is True, other-
wise they will both have the tag tag1.
do_path_update Used internally, you should never change it.
set_link_map(eld, value_to_link_map, only_set_if_no_existing_link=False)
Sets links for item values in eld. Note: this method doesn’t change values not in the value_to_link_map
Parameters
field the lookup name
value_to_link_map dict(eld_value:link, …). Note that these are values, not eld
ids.
Returns
books changed by setting the link
set_metadata(book_id, mi, ignore_errors=False, force_changes=False, set_title=True, set_authors=True,
allow_case_change=False)
Set metadata for the book id from the Metadata object mi
Setting force_changes=True will force set_metadata to update elds even if mi contains empty values. In
this case, ‘None’ is distinguished from ‘empty’. If mi.XXX is None, the XXX is not replaced, otherwise it
is. The tags, identiers, and cover attributes are special cases. Tags and identiers cannot be set to None so
they will always be replaced if force_changes is true. You must ensure that mi contains the values you want
378 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
the book to have. Covers are always changed if a new cover is provided, but are never deleted. Also note that
force_changes has no eect on setting title or authors.
set_notes_for(eld, item_id, doc: str, searchable_text: str = '', resource_hashes=(),
remove_unused_resources=False) int
Set the notes document. If the searchable text is dierent from the document, specify it as search-
able_text. If the document references resources their hashes must be present in resource_hashes. Set re-
move_unused_resources to True to cleanup unused resources, note that updating a note automatically cleans
up resources pertaining to that note anyway.
set_pref(name, val, namespace=None)
Set the specied preference to the specied value. See also pref() (page 376).
split_if_is_multiple_composite(f, val)
If f is a composite column lookup key and the column is is_multiple then split v into unique non-empty
values. The comparison is case sensitive. Order is not preserved. Return a list() for compatibility with proxy
metadata eld getters, for example tags.
tags_older_than(tag, delta=None, must_have_tag=None, must_have_authors=None)
Return the ids of all books having the tag tag that are older than the specied time. tag comparison is case
insensitive.
Parameters
delta A timedelta object or None. If None, then all ids with the tag are returned.
must_have_tag If not None the list of matches will be restricted to books that have
this tag
must_have_authors A list of authors. If not None the list of matches will be restricted
to books that have these authors (case insensitive).
unretire_note_for(eld, item_id) int
Unretire a previously retired note for the specied item. Notes are retired when an item is removed from the
database
update_annotations(annot_id_map)
Update annotations.
user_categories_for_books(book_ids, proxy_metadata_map=None)
Return the user categories for the specied books. proxy_metadata_map is optional and is useful for a perfor-
mance boost, in contexts where a ProxyMetadata object for the books already exists. It should be a mapping
of book_ids to their corresponding ProxyMetadata objects.
14.9.2 API documentation for the e-book editing tools
The e-book editing tools consist of a calibre.ebooks.oeb.polish.container.Container (page 380)
object that represents a book as a collection of HTML + resource les, and various tools that can be used to perform
operations on the container. All the tools are in the form of module level functions in the various calibre.ebooks.
oeb.polish.* modules. You obtain a container object for a book at a path like this:
from calibre.ebooks.oeb.polish.container import get_container
container = get_container('Path to book file', tweak_mode=True)
If you are writing a plugin for the E-book editor, you get the current container for the book being edited like this:
14.9. API documentation for various parts of calibre 379
calibre User Manual, Release 7.19.0
from calibre.gui2.tweak_book import current_container
container = current_container()
if container is None:
report_error # No book has been opened yet
The Container object
class calibre.ebooks.oeb.polish.container.Container(rootpath, opfpath, log,
clone_data=None)
A container represents an open e-book as a folder full of les and an OPF le. There are two important concepts:
The root folder. This is the base of the e-book. All the e-books les are inside this folder or in its sub-folders.
Names: These are paths to the books’ les relative to the root folder. They always contain POSIX separators
and are unquoted. They can be thought of as canonical identiers for les in the book. Most methods on the
container object work with names. Names are always in the NFC Unicode normal form.
Clones: the container object supports ecient on-disk cloning, which is used to implement checkpoints in the
e-book editor. In order to make this work, you should never access les on the lesystem directly. Instead,
use raw_data() (page 382) or open() (page 382) to read/write to component les in the book.
When converting between hrefs and names use the methods provided by this class, they assume all hrefs are quoted.
abspath_to_name(fullpath, root=None)
Convert an absolute path to a canonical name relative to root
Parameters
root The base folder. By default the root for this container object is used.
add_file(name, data, media_type=None, spine_index=None, modify_name_if_needed=False,
process_manifest_item=None)
Add a le to this container. Entries for the le are automatically created in the OPF manifest and spine (if
the le is a text document)
add_name_to_manifest(name, process_manifest_item=None)
Add an entry to the manifest for a le with the specied name. Returns the manifest id.
add_properties(name, *properties)
Add the specied properties to the manifest item identied by name.
apply_unique_properties(name, *properties)
Ensure that the specied properties are set on only the manifest item identied by name. You can pass None
as the name to remove the property from all items.
book_type = 'oeb'
The type of book (epub for EPUB les and azw3 for AZW3 les)
commit(outpath=None, keep_parsed=False)
Commit all dirtied parsed objects to the lesystem and write out the e-book le at outpath.
Parameters
output The path to write the saved e-book le to. If None, the path of the original book
le is used.
keep_parsed If True the parsed representations of committed items are kept in the
cache.
380 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
commit_item(name, keep_parsed=False)
Commit a parsed object to disk (it is serialized and written to the underlying le). If keep_parsed is True
the parsed representation is retained in the cache. See also: parsed() (page 382)
dirty(name)
Mark the parsed object corresponding to name as dirty. See also: parsed() (page 382).
exists(name)
True i a le/folder corresponding to the canonical name exists. Note that this function suers from the
limitations of the underlying OS lesystem, in particular case (in)sensitivity. So on a case insensitive lesystem
this will return True even if the case of name is dierent from the case of the underlying lesystem le. See
also has_name() (page 381)
filesize(name)
Return the size in bytes of the le represented by the specied canonical name. Automatically handles dirtied
parsed objects. See also: parsed() (page 382)
generate_item(name, id_prex=None, media_type=None, unique_href=True)
Add an item to the manifest with href derived from the given name. Ensures uniqueness of href and id
automatically. Returns generated item.
get_file_path_for_processing(name, allow_modication=True)
Similar to open() except that it returns a le path, instead of an open le object.
property guide_type_map
Mapping of guide type to canonical name
has_name(name)
Return True i a le with the same canonical name as that specied exists. Unlike exists() (page 381)
this method is always case-sensitive.
href_to_name(href, base=None)
Convert an href (relative to base) to a name. base must be a name or None, in which case self.root is used.
insert_into_xml(parent, item, index=None)
Insert item into parent (or append if index is None), xing indentation. Only works with self closing items.
is_dir = False
If this container represents an unzipped book (a directory)
iterlinks(name, get_line_numbers=True)
Iterate over all links in name. If get_line_numbers is True the yields results of the form (link, line_number,
oset). Where line_number is the line_number at which the link occurs and oset is the number of characters
from the start of the line. Note that oset could actually encompass several lines if not zero.
make_name_unique(name)
Ensure that name does not already exist in this book. If it does, return a modied version that does not exist.
manifest_has_name(name)
Return True if the manifest has an entry corresponding to name
property manifest_id_map
Mapping of manifest id to canonical names
manifest_items_of_type(predicate)
The names of all manifest items whose media-type matches predicate. predicate can be a set, a list, a string
or a function taking a single argument, which will be called with the media-type.
14.9. API documentation for various parts of calibre 381
calibre User Manual, Release 7.19.0
manifest_items_with_property(property_name)
All manifest items that have the specied property
property manifest_type_map
Mapping of manifest media-type to list of canonical names of that media-type
property mi
The metadata of this book as a Metadata object. Note that this object is constructed on the y every time this
property is requested, so use it sparingly.
name_to_abspath(name)
Convert a canonical name to an absolute OS dependent path
name_to_href(name, base=None)
Convert a name to a href relative to base, which must be a name or None in which case self.root is used as
the base
property names_that_must_not_be_changed
Set of names that must never be renamed. Depends on the e-book le format.
property names_that_must_not_be_removed
Set of names that must never be deleted from the container. Depends on the e-book le format.
property names_that_need_not_be_manifested
Set of names that are allowed to be missing from the manifest. Depends on the e-book le format.
open(name, mode='rb')
Open the le pointed to by name for direct read/write. Note that this will commit the le if it is dirtied and
remove it from the parse cache. You must nish with this le before accessing the parsed version of it again,
or bad things will happen.
property opf
The parsed OPF le
opf_get_or_create(name)
Convenience method to either return the rst XML element with the specied name or create it under the
opf:package element and then return it, if it does not already exist.
property opf_version
The version set on the OPF’s <package> element
property opf_version_parsed
The version set on the OPF’s <package> element as a tuple of integers
opf_xpath(expr)
Convenience method to evaluate an XPath expression on the OPF le, has the opf: and dc: namespace prexes
pre-dened.
parsed(name)
Return a parsed representation of the le specied by name. For HTML and XML les an lxml tree is re-
turned. For CSS les a css_parser stylesheet is returned. Note that parsed objects are cached for performance.
If you make any changes to the parsed object, you must call dirty() (page 381) so that the container knows
to update the cache. See also replace() (page 383).
raw_data(name, decode=True, normalize_to_nfc=True)
Return the raw data corresponding to the le specied by name
Parameters
382 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
decode If True and the le has a text based MIME type, decode it and return a unicode
object instead of raw bytes.
normalize_to_nfc If True the returned unicode object is normalized to the NFC
normal form as is required for the EPUB and AZW3 le formats.
relpath(path, base=None)
Convert an absolute path (with os separators) to a path relative to base (defaults to self.root). The relative
path is not a name. Use abspath_to_name() (page 380) for that.
remove_from_spine(spine_items, remove_if_no_longer_in_spine=True)
Remove the specied items (by canonical name) from the spine. If re-
move_if_no_longer_in_spine is True, the items are also deleted from the book, not just
from the spine.
remove_from_xml(item)
Removes item from parent, xing indentation (works only with self closing items)
remove_item(name, remove_from_guide=True)
Remove the item identied by name from this container. This removes all references to the item in the OPF
manifest, guide and spine as well as from any internal caches.
rename(current_name, new_name)
Renames a le from current_name to new_name. It automatically rebases all links inside the le if the folder
the le is in changes. Note however, that links are not updated in the other les that could reference this le.
This is for performance, such updates should be done once, in bulk.
replace(name, obj)
Replace the parsed object corresponding to name with obj, which must be a similar object, i.e. an lxml tree
for HTML/XML or a css_parser stylesheet for a CSS le.
replace_links(name, replace_func)
Replace all links in name using replace_func, which must be a callable that accepts a URL and returns the
replaced URL. It must also have a ‘replaced’ attribute that is set to True if any actual replacement is done.
Convenient ways of creating such callables are using the LinkReplacer and LinkRebaser classes.
serialize_item(name)
Convert a parsed object (identied by canonical name) into a bytestring. See parsed() (page 382).
set_spine(spine_items)
Set the spine to be spine_items where spine_items is an iterable of the form (name, linear). Will raise an
error if one of the names is not present in the manifest.
property spine_items
An iterator yielding the path for every item in the books’ spine. See also: spine_iter (page 383) and
spine_items (page 383).
property spine_iter
An iterator that yields item, name is_linear for every item in the books’ spine. item is the lxml element, name
is the canonical le name and is_linear is True if the item is linear. See also: spine_names (page 383)
and spine_items (page 383).
property spine_names
An iterator yielding name and is_linear for every item in the books’ spine. See also: spine_iter (page 383)
and spine_items (page 383).
14.9. API documentation for various parts of calibre 383
calibre User Manual, Release 7.19.0
Managing component les in a container
calibre.ebooks.oeb.polish.replace.replace_links(container, link_map, frag_map=<function
<lambda>>, replace_in_opf=False)
Replace links to les in the container. Will iterate over all les in the container and change the specied links in
them.
Parameters
link_map A mapping of old canonical name to new canonical name. For example:
{'images/old.png': 'images/new.png'}
frag_map A callable that takes two arguments (name, anchor) and returns a new
anchor. This is useful if you need to change the anchors in HTML les. By default, it does
nothing.
replace_in_opf If False, links are not replaced in the OPF le.
calibre.ebooks.oeb.polish.replace.rename_files(container, le_map)
Rename les in the container, automatically updating all links to them.
Parameters
file_map A mapping of old canonical name to new canonical name, for example: {'text/
chapter1.html': 'chapter1.html'}.
calibre.ebooks.oeb.polish.replace.get_recommended_folders(container, names)
Return the folders that are recommended for the given lenames. The recommendation is based on where the
majority of les of the same type are located in the container. If no les of a particular type are present, the
recommended folder is assumed to be the folder containing the OPF le.
Pretty printing and auto xing parse errors
calibre.ebooks.oeb.polish.pretty.fix_html(container, raw)
Fix any parsing errors in the HTML represented as a string in raw. Fixing is done using the HTML5 parsing
algorithm.
calibre.ebooks.oeb.polish.pretty.fix_all_html(container)
Fix any parsing errors in all HTML les in the container. Fixing is done using the HTML5 parsing algorithm.
calibre.ebooks.oeb.polish.pretty.pretty_html(container, name, raw)
Pretty print the HTML represented as a string in raw
calibre.ebooks.oeb.polish.pretty.pretty_css(container, name, raw)
Pretty print the CSS represented as a string in raw
calibre.ebooks.oeb.polish.pretty.pretty_xml(container, name, raw)
Pretty print the XML represented as a string in raw. If name is the name of the OPF, extra OPF-specic prettying
is performed.
calibre.ebooks.oeb.polish.pretty.pretty_all(container)
Pretty print all HTML/CSS/XML les in the container
384 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
Managing book jackets
calibre.ebooks.oeb.polish.jacket.remove_jacket(container)
Remove an existing jacket, if any. Returns False if no existing jacket was found.
calibre.ebooks.oeb.polish.jacket.add_or_replace_jacket(container)
Either create a new jacket from the book’s metadata or replace an existing jacket. Returns True if an existing jacket
was replaced.
Splitting and merging of les
calibre.ebooks.oeb.polish.split.split(container, name, loc_or_xpath, before=True, totals=None)
Split the le specied by name at the position specied by loc_or_xpath. Splitting automatically migrates all links
and references to the aected les.
Parameters
loc_or_xpath Should be an XPath expression such as //h:div[@id=”split_here”]. Can
also be a loc which is used internally to implement splitting in the preview panel.
before If True the split occurs before the identied element otherwise after it.
totals Used internally
calibre.ebooks.oeb.polish.split.multisplit(container, name, xpath, before=True)
Split the specied le at multiple locations (all tags that match the specied XPath expression). See also: split()
(page 385). Splitting automatically migrates all links and references to the aected les.
Parameters
before If True the splits occur before the identied element otherwise after it.
calibre.ebooks.oeb.polish.split.merge(container, category, names, master)
Merge the specied les into a single le, automatically migrating all links and references to the aected les. The
le must all either be HTML or CSS les.
Parameters
category Must be either 'text' for HTML les or 'styles' for CSS les
names The list of les to be merged
master Which of the merged les is the master le, that is, the le that will remain after
merging.
Managing covers
calibre.ebooks.oeb.polish.cover.set_cover(container, cover_path, report=None, options=None)
Set the cover of the book to the image pointed to by cover_path.
Parameters
cover_path Either the absolute path to an image le or the canonical name of an image
in the book. When using an image in the book, you must also set options, see below.
report An optional callable that takes a single argument. It will be called with information
about the tasks being processed.
14.9. API documentation for various parts of calibre 385
calibre User Manual, Release 7.19.0
options None or a dictionary that controls how the cover is set. The dictionary can
have entries: keep_aspect: True or False (Preserve aspect ratio of covers in EPUB) no_svg:
True or False (Use an SVG cover wrapper in the EPUB titlepage) existing: True or False
(cover_path refers to an existing image in the book)
calibre.ebooks.oeb.polish.cover.mark_as_cover(container, name)
Mark the specied image as the cover image.
calibre.ebooks.oeb.polish.cover.mark_as_titlepage(container, name, move_to_start=True)
Mark the specied HTML le as the titlepage of the EPUB.
Parameters
move_to_start If True the HTML le is moved to the start of the spine
Working with CSS
calibre.ebooks.oeb.polish.fonts.change_font(container, old_name, new_name=None)
Change a font family from old_name to new_name. Changes all occurrences of the font family in stylesheets, style
tags and style attributes. If the old_name refers to an embedded font, it is removed. You can set new_name to
None to remove the font family instead of changing it.
calibre.ebooks.oeb.polish.css.remove_unused_css(container, report=None,
remove_unused_classes=False,
merge_rules=False,
merge_rules_with_identical_properties=False,
remove_unreferenced_sheets=False)
Remove all unused CSS rules from the book. An unused CSS rule is one that does not match any actual content.
Parameters
report An optional callable that takes a single argument. It is called with information
about the operations being performed.
remove_unused_classes If True, class attributes in the HTML that do not match any
CSS rules are also removed.
merge_rules If True, rules with identical selectors are merged.
merge_rules_with_identical_properties If True, rules with identical prop-
erties are merged.
remove_unreferenced_sheets If True, stylesheets that are not referenced by any
content are removed
calibre.ebooks.oeb.polish.css.filter_css(container, properties, names=())
Remove the specied CSS properties from all CSS rules in the book.
Parameters
properties – Set of properties to remove. For example: {'font-family',
'color'}.
names The les from which to remove the properties. Defaults to all HTML and CSS les
in the book.
386 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
Working with the Table of Contents
calibre.ebooks.oeb.polish.toc.from_xpaths(container, xpaths, prefer_title=False)
Generate a Table of Contents from a list of XPath expressions. Each expression in the list corresponds to a level of
the generate ToC. For example: ['//h:h1', '//h:h2', '//h:h3'] will generate a three level Table of
Contents from the <h1>, <h2> and <h3> tags.
calibre.ebooks.oeb.polish.toc.from_links(container)
Generate a Table of Contents from links in the book.
calibre.ebooks.oeb.polish.toc.from_files(container)
Generate a Table of Contents from les in the book.
calibre.ebooks.oeb.polish.toc.create_inline_toc(container, title=None)
Create an inline (HTML) Table of Contents from an existing NCX Table of Contents.
Parameters
title The title for this table of contents.
Edit book tool
class calibre.gui2.tweak_book.plugin.Tool
Bases: object
The base class for individual tools in an Edit Book plugin. Useful members include:
self.plugin: A reference to the calibre.customize.Plugin (page 258) object to which this
tool belongs.
self. boss (page 387)
self. gui (page 387)
Methods that must be overridden in sub classes:
create_action() (page 388)
register_shortcut() (page 388)
name = None
Set this to a unique name it will be used as a key
allowed_in_toolbar = True
If True the user can choose to place this tool in the plugins toolbar
allowed_in_menu = True
If True the user can choose to place this tool in the plugins menu
toolbar_button_popup_mode = 'delayed'
The popup mode for the menu (if any) of the toolbar button. Possible values are ‘delayed’, ‘instant’, ‘button’
property boss
The calibre.gui2.tweak_book.boss.Boss (page 389) object. Used to control the user interface.
property gui
The main window of the user interface
14.9. API documentation for various parts of calibre 387
calibre User Manual, Release 7.19.0
property current_container
Return the current calibre.ebooks.oeb.polish.container.Container (page 380) object
that represents the book being edited.
register_shortcut(qaction, unique_name, default_keys=(), short_text=None, description=None,
**extra_data)
Register a keyboard shortcut that will trigger the specied qaction. This keyboard shortcut will become
automatically customizable by the user in the Keyboard shortcuts section of the editor preferences.
Parameters
qaction A QAction object, it will be triggered when the congured key combination is
pressed by the user.
unique_name
A unique name for this shortcut/action. It will be used internally, it must
not be shared by any other actions in this plugin.
default_keys A list of the default keyboard shortcuts. If not specied no default
shortcuts will be set. If the shortcuts specied here conict with either builtin shortcuts
or shortcuts from user conguration/other plugins, they will be ignored. In that case,
users will have to congure the shortcuts manually via Preferences. For example: de-
fault_keys=('Ctrl+J', 'F9').
short_text An optional short description of this action. If not specied the text from
the QAction will be used.
description An optional longer description of this action, it will be used in the pref-
erences entry for this shortcut.
create_action(for_toolbar=True)
Create a QAction that will be added to either the plugins toolbar or the plugins menu depending on
for_toolbar. For example:
def create_action(self, for_toolbar=True):
ac = QAction(get_icons('myicon.png'), 'Do something')
if for_toolbar:
# We want the toolbar button to have a popup menu
menu = QMenu()
ac.setMenu(menu)
menu.addAction('Do something else')
subaction = menu.addAction('And another')
# Register a keyboard shortcut for this toolbar action be
# careful to do this for only one of the toolbar action or
# the menu action, not both.
self.register_shortcut(ac, 'some-unique-name', default_keys=('Ctrl+K',
,))
return ac
µ See also
Method register_shortcut() (page 388).
388 Chapter 14. Setting up a calibre development environment
calibre User Manual, Release 7.19.0
Controlling the editor’s user interface
The e-book editor’s user interface is controlled by a single global Boss object. This has many useful methods that can be
used in plugin code to perform common tasks.
class calibre.gui2.tweak_book.boss.Boss(parent, notify=None)
add_savepoint(msg)
Create a restore checkpoint with the name specied as msg
apply_container_update_to_gui(mark_as_modied=True)
Update all the components of the user interface to reect the latest data in the current book container.
Parameters
mark_as_modified If True, the book will be marked as modied, so the user will be
prompted to save it when quitting.
close_editor(name)
Close the editor that is editing the le specied by name
commit_all_editors_to_container()
Commit any changes that the user has made to les open in editors to the container. You should call this
method before performing any actions on the current container
property currently_editing
Return the name of the le being edited currently or None if no le is being edited
edit_file(name, syntax=None, use_template=None)
Open the le specied by name in an editor
Parameters
syntax The media type of the le, for example, 'text/html'. If not specied it is
guessed from the le extension.
use_template A template to initialize the opened editor with
open_book(path=None, edit_le=None, clear_notify_data=True, open_folder=False, search_text=None)
Open the e-book at path for editing. Will show an error if the e-book is not in a supported format or the
current book has unsaved changes.
Parameters
edit_file The name of a le inside the newly opened book to start editing. Can also be
a list of names.
rewind_savepoint()
Undo the previous creation of a restore checkpoint, useful if you create a checkpoint, then abort the operation
with no changes
save_book()
Save the book. Saving is performed in the background
set_modified()
Mark the book as having been modied
show_current_diff(allow_revert=True, to_container=None)
Show the changes to the book from its last checkpointed state
Parameters
14.9. API documentation for various parts of calibre 389
calibre User Manual, Release 7.19.0
allow_revert If True the di dialog will have a button to allow the user to revert all
changes
to_container A container object to compare the current container to. If None, the
previously checkpointed container is used
show_editor(name)
Show the editor that is editing the le specied by name
sync_preview_to_editor()
Sync the position of the preview panel to the current cursor position in the current editor
390 Chapter 14. Setting up a calibre development environment
CHAPTER
FIFTEEN
DIGITAL RIGHTS MANAGEMENT (DRM)
Digital Rights Management (DRM) is a generic term for access control technologies that can be used by hardware man-
ufacturers, publishers, copyright holders and individuals to try to impose limitations on the usage of digital content and
devices. It is also, sometimes, disparagingly described as Digital Restrictions Management. The term is used to describe
any technology which inhibits uses (legitimate or otherwise) of digital content that were not desired or foreseen by the
content provider. The term generally doesn’t refer to other forms of copy protection which can be circumvented without
modifying the le or device, such as serial numbers or key-les. It can also refer to restrictions associated with specic
instances of digital works or devices. DRM technologies attempt to control use of digital media by preventing access,
copying or conversion to other formats by end users. See Wikipedia
136
.
15.1 What does DRM imply for me personally?
When you buy an e-book with DRM you don’t really own it but have purchased the permission to use it in a manner
dictated to you by the seller. DRM limits what you can do with e-books you have “bought”. Often people who buy books
with DRM are unaware of the extent of these restrictions. These restrictions prevent you from reformatting the e-book to
your liking, including making stylistic changes like adjusting the font sizes, although there is software that empowers you
to do such things for non DRM books. People are often surprised that an e-book they have bought in a particular format
cannot be converted to another format if the e-book has DRM. So if you have an Amazon Kindle and buy a book sold by
Barnes and Nobles, you should know that if that e-book has DRM you will not be able to read it on your Kindle. Notice
that I am talking about a book you buy, not steal or pirate but BUY.
15.2 What does DRM do for authors?
Publishers of DRMed e-books argue that the DRM is all for the sake of authors and to protect their artistic integrity and
prevent piracy. But DRM does NOT prevent piracy. People who want to pirate content or use pirated content still do it
and succeed. The three major DRM schemes for e-books today are run by Amazon, Adobe and Barnes and Noble and all
three DRM schemes have been cracked. All DRM does is inconvenience legitimate users. It can be argued that it actually
harms authors as people who would have bought the book choose to nd a pirated version as they are not willing to put
up with DRM. Those that would pirate in the absence of DRM do so in its presence as well. To reiterate, the key point
is that DRM does not prevent piracy. So DRM is not only pointless and harmful to buyers of e-books but also a waste of
money.
136
https://en.wikipedia.org/wiki/Digital_rights_management
391
calibre User Manual, Release 7.19.0
15.3 DRM and freedom
Although digital content can be used to make information as well as creative works easily available to everyone and
empower humanity, this is not in the interests of some publishers who want to steer people away from this possibility of
freedom simply to maintain their relevance in world developing so fast that they can’t keep up.
15.4 Why does calibre not support DRM?
calibre is open source software while DRM by its very nature is closed. If calibre were to support opening or viewing
DRM les it could be trivially modied to be used as a tool for DRM removal which is illegal under today’s laws. Open
source software and DRM are a clash of principles. While DRM is all about controlling the user, open source software
is about empowering the user. The two simply can not coexist.
15.5 What is calibre’s view on content providers?
We rmly believe that authors and other content providers should be compensated for their eorts, but DRM is not the
way to go about it. We are developing this database of DRM-free e-books from various sources to help you nd DRM-free
alternatives and to help independent authors and publishers of DRM-free e-books publicize their content. We hope you
will nd this useful and we request that you do not pirate the content made available to you here.
15.6 How can I help ght DRM?
As somebody who reads and buys e-books you can help ght DRM. Do not buy e-books with DRM. There are some
publishers who publish DRM-free e-books. Make an eort to see if they carry the e-book you are looking for. If you like
books by certain independent authors that sell DRM-free e-books and you can aord it make donations to them. This
is money well spent as their e-books tend to be cheaper (there may be exceptions) than the ones you would buy from
publishers of DRMed books and would probably work on all devices you own in the future saving you the cost of buying
the e-book again. Do not discourage publishers and authors of DRM-free e-books by pirating their content. Content
providers deserve compensation for their eorts. Do not punish them for trying to make your reading experience better
by making available DRM-free e-books. In the long run this is detrimental to you. If you have bought books from sellers
that carry both DRMed as well as DRM-free books, not knowing if they carry DRM or not make it a point to leave a
comment or review on the website informing future buyers of its DRM status. Many sellers do not think it important to
clearly indicate to their buyers if an e-book carries DRM or not. Here
137
you will nd a guide to DRM-free living.
137
https://www.defectivebydesign.org/guide/ebooks
392 Chapter 15. Digital Rights Management (DRM)
CHAPTER
SIXTEEN
GLOSSARY
RSS
RSS (Really Simple Syndication) is a web feed format that is used to publish frequently updated content, like news
articles, blog posts, etc. It is a format that is particularly suited to being read by computers, and is therefore the
preferred way of getting content from the web into an e-book. There are many other feed formats in use on the
Internet, and calibre understands most of them. In particular, it has good support for the ATOM format, which is
commonly used for blogs.
recipe
A recipe is a set of instructions that teach calibre how to convert an online news source, such as a magazine or a
blog, into an e-book. A recipe is essentially Python
138
code. As such, it is capable of converting arbitrarily complex
news sources into e-books. At the simplest level, it is just a set of variables, such as URLs, that give calibre enough
information to go out onto the Internet and download the news.
HTML
HTML (Hyper Text Mark-Up Language), a subset of Standard Generalized Mark-Up Language (SGML) for elec-
tronic publishing, is the specic standard used for the World Wide Web.
CSS
CSS (Cascading Style Sheets) is a language used to describe how an HTML document should be rendered (visual
styling).
API
API (Application Programming Interface) is a source code interface that a library provides to support requests for
services to be made of it by computer programs.
LRF
LRF The e-book format that is read by the SONY e-book readers.
URL
URL (Uniform Resource Locator) for example: http://example.com
regexp
Regular expressions provide a concise and exible means for identifying strings of text of interest, such as par-
ticular characters, words, or patterns of characters. See the tutorial (page 215) for an introduction to regular
expressions.
138
https://www.python.org
393
calibre User Manual, Release 7.19.0
394 Chapter 16. Glossary
PYTHON MODULE INDEX
c
calibre.customize, 257
calibre.customize.conversion, 267
calibre.db.cache, 369
calibre.devices.interface, 270
calibre.ebooks.metadata.book.base, 211
calibre.ebooks.metadata.sources.base,
264
calibre.ebooks.oeb.polish.container, 379
calibre.ebooks.oeb.polish.cover, 385
calibre.ebooks.oeb.polish.css, 386
calibre.ebooks.oeb.polish.jacket, 385
calibre.ebooks.oeb.polish.pretty, 384
calibre.ebooks.oeb.polish.replace, 384
calibre.ebooks.oeb.polish.split, 385
calibre.ebooks.oeb.polish.toc, 387
calibre.gui2.tweak_book.boss, 389
calibre.utils.formatter_functions, 191
calibre.web.feeds.news, 39
395
calibre User Manual, Release 7.19.0
396 Python Module Index
INDEX
Symbols
-1
calibredb-add command line option,
315
-H
ebook-polish command line option, 354
-I
calibredb-add command line option,
315
fetch-ebook-metadata command line
option, 356
-S
calibredb-add command line option,
315
-T
calibredb-add command line option,
315
-U
ebook-polish command line option, 355
--access-log
calibre-server command line option,
307
--add
calibredb-add command line option,
315
--add-alt-text-to-img
ebook-convert command line option,
331
--add-plugin
calibre-customize command line op-
tion, 304
--add-simple-plugin
calibre-debug command line option,
305
--add-soft-hyphens
ebook-polish command line option, 354
--ajax-timeout
calibre-server command line option,
307
--all
calibredb-backup_metadata command
line option, 323
calibredb-export command line op-
tion
, 317
--allow-local-files-outside-root
ebook-convert-html-input command
line option, 336
--allowed-plugin
fetch-ebook-metadata command line
option
, 356
--append
calibredb-set_custom command line
option, 321
--as-extra-data-file
calibredb-add_format command line
option
, 316
--as-opf
calibredb-show_metadata command
line option, 316
--ascending
calibredb-list command line option,
313
--asciiize
ebook-convert command line option,
328
--attachment
calibre-smtp command line option, 311
--auth-mode
calibre-server command line option,
307
--author-sort
ebook-convert command line option,
333
ebook-meta command line option
, 352
--authors
calibredb-add command line option,
314
ebook-convert command line option,
333
ebook-meta command line option
, 352
fetch-ebook-metadata command line
option, 356
--auto-reload
calibre-server command line option,
397
calibre User Manual, Release 7.19.0
307
--automerge
calibredb-add command line option,
314
--ban-after
calibre-server command line option,
307
--ban-for
calibre-server command line option,
307
--base-dir
web2disk command line option, 359
--base-font-size
ebook-convert command line option,
328
--book-list-mode
calibre-server command line option,
307
--book-producer
ebook-convert command line option,
333
ebook-meta command line option, 352
--breadth-first
ebook-convert-html-input command
line option, 336
--build-plugin
calibre-customize command line op-
tion, 304
--cafile
calibre-smtp command line option, 311
--catalog-title
calibredb-catalog command line op-
tion, 319
--categories
calibredb-list_categories command
line option, 322
--category
ebook-meta command line option, 352
--change-justification
ebook-convert command line option,
328
--chapter
ebook-convert command line option,
331
--chapter-mark
ebook-convert command line option,
331
--colors
ebook-convert-comic-input command
line option, 334
--comic-image-size
ebook-convert-comic-input command
line option, 334
--command
calibre-debug command line option,
305
--comments
ebook-convert command line option,
333
ebook-meta command line option, 352
--compress-images
ebook-polish command line option, 354
--compress-min-size
calibre-server command line option,
307
--continue
ebook-viewer command line option, 355
--cover
calibredb-add command line option,
315
ebook-convert command line option,
333
ebook-meta command line option, 352
ebook-polish command line option, 354
fetch-ebook-metadata command line
option, 356
--cross-reference-authors
calibredb-catalog command line op-
tion, 319
--csv
calibredb-check_library command
line option, 322
calibredb-list_categories command
line option, 322
--custom-list-template
calibre-server command line option,
307
--custom-size
ebook-convert-pdf-output command
line option, 347
--customize-plugin
calibre-customize command line op-
tion, 304
--daemonize
calibre-server command line option,
307
--date
ebook-meta command line option, 352
--debug-device-driver
calibre-debug command line option,
305
--debug-pipeline
calibredb-catalog command line op-
tion, 319
ebook-convert command line option,
334
--default-programs
calibre-debug command line option,
398 Index
calibre User Manual, Release 7.19.0
305
--delay
web2disk command line option, 359
--despeckle
ebook-convert-comic-input command
line option, 334
--detach
calibre command line option, 303
ebook-edit command line option, 352
ebook-viewer command line option, 355
--details
calibredb-custom_columns command
line option, 321
--dialect
calibredb-list_categories command
line option, 323
--diff
calibre-debug command line option,
305
--disable-allow-socket-preallocation
calibre-server command line option,
308
--disable-auth
calibre-server command line option,
308
--disable-dehyphenate
ebook-convert command line option,
330
--disable-delete-blank-paragraphs
ebook-convert command line option,
330
--disable-fallback-to-detected-
interface
calibre-server command line option,
308
--disable-fix-indents
ebook-convert command line option,
330
--disable-font-rescaling
ebook-convert command line option,
328
--disable-format-scene-breaks
ebook-convert command line option,
330
--disable-hyphenation
lrfviewer command line option, 358
--disable-italicize-common-cases
ebook-convert command line option,
330
--disable-local-write
calibre-server command line option,
308
--disable-log-not-found
calibre-server command line option,
308
--disable-markup-chapter-headings
ebook-convert command line option,
330
--disable-plugin
calibre-customize command line op-
tion, 304
--disable-remove-fake-margins
ebook-convert command line option,
331
--disable-renumber-headings
ebook-convert command line option,
330
--disable-trim
ebook-convert-comic-input command
line option, 334
--disable-unwrap-lines
ebook-convert command line option,
330
--disable-use-bonjour
calibre-server command line option,
308
--disable-use-sendfile
calibre-server command line option,
308
--display
calibredb-add_custom_column command
line option, 320
--displayed-fields
calibre-server command line option,
308
--do-not-match-on-related-words
calibredb-fts_search command line
option, 325
--docx-custom-page-size
ebook-convert-docx-output command
line option, 341
--docx-inline-subsup
ebook-convert-docx-input command
line option, 336
--docx-no-cover
ebook-convert-docx-input command
line option, 336
ebook-convert-docx-output command
line option, 341
--docx-no-pagebreaks-between-notes
ebook-convert-docx-input command
line option, 336
--docx-no-toc
ebook-convert-docx-output command
line option, 341
--docx-page-margin-bottom
ebook-convert-docx-output command
line option, 341
Index 399
calibre User Manual, Release 7.19.0
--docx-page-margin-left
ebook-convert-docx-output command
line option, 341
--docx-page-margin-right
ebook-convert-docx-output command
line option, 341
--docx-page-margin-top
ebook-convert-docx-output command
line option, 341
--docx-page-size
ebook-convert-docx-output command
line option, 341
--dont-add-comic-pages-to-toc
ebook-convert-comic-input command
line option, 334
--dont-asciiize
calibredb-export command line op-
tion, 317
--dont-compress
ebook-convert-azw3-output command
line option, 341
ebook-convert-mobi-output command
line option, 345
--dont-download-recipe
ebook-convert-recipe-input command
line option, 339
--dont-download-stylesheets
web2disk command line option, 359
--dont-grayscale
ebook-convert-comic-input command
line option, 335
--dont-normalize
ebook-convert-comic-input command
line option, 335
--dont-output-resources
lrf2lrs command line option, 357
--dont-package
ebook-convert-html-input command
line option, 336
--dont-replace
calibredb-add_format command line
option, 316
--dont-save-cover
calibredb-export command line op-
tion, 317
--dont-save-extra-files
calibredb-export command line op-
tion, 317
--dont-sharpen
ebook-convert-comic-input command
line option, 335
--dont-split-on-page-breaks
ebook-convert-epub-output command
line option, 342
--dont-update-metadata
calibredb-export command line op-
tion, 317
--dont-verify-server-certificate
calibre-smtp command line option, 311
--dont-write-opf
calibredb-export command line op-
tion, 317
--download-external-resources
ebook-polish command line option, 354
--duplicate-links-in-toc
ebook-convert command line option,
332
--duplicates
calibredb-add command line option,
315
--edit-book
calibre-debug command line option,
305
--embed-all-fonts
ebook-convert command line option,
328
--embed-font-family
ebook-convert command line option,
328
--embed-fonts
ebook-polish command line option, 354
--empty
calibredb-add command line option,
315
--enable-allow-socket-preallocation
calibre-server command line option,
308
--enable-auth
calibre-server command line option,
308
--enable-autorotation
ebook-convert-lrf-output command
line option, 344
--enable-fallback-to-detected-
interface
calibre-server command line option,
308
--enable-heuristics
ebook-convert command line option,
330
--enable-local-write
calibre-server command line option,
308
--enable-log-not-found
calibre-server command line option,
308
--enable-plugin
400 Index
calibre User Manual, Release 7.19.0
calibre-customize command line op-
tion, 304
--enable-use-bonjour
calibre-server command line option,
308
--enable-use-sendfile
calibre-server command line option,
308
--encoding
web2disk command line option, 359
--encryption-method
calibre-smtp command line option, 311
--epub-flatten
ebook-convert-epub-output command
line option, 342
--epub-inline-toc
ebook-convert-epub-output command
line option, 342
--epub-max-image-size
ebook-convert-epub-output command
line option, 342
--epub-toc-at-end
ebook-convert-epub-output command
line option, 342
--epub-version
ebook-convert-epub-output command
line option, 342
--exclude-genre
calibredb-catalog command line op-
tion, 319
--exclusion-rules
calibredb-catalog command line op-
tion, 319
--exec-file
calibre-debug command line option,
305
--expand-css
ebook-convert command line option,
328
--explode-book
calibre-debug command line option,
305
--export-all-calibre-data
calibre-debug command line option,
305
--extra-css
ebook-convert command line option,
328
--extract-to
ebook-convert-azw3-output command
line option, 341
ebook-convert-docx-output command
line option, 342
ebook-convert-epub-output command
line option, 342
ebook-convert-html-output command
line option, 344
ebook-convert-mobi-output command
line option, 345
--fb2-genre
ebook-convert-fb2-output command
line option, 343
--field
calibredb-set_metadata command line
option, 317
--fields
calibredb-list command line option,
313
--filter-css
ebook-convert command line option,
328
--filter-regexp
web2disk command line option, 359
--fix-multiprocessing
calibre-debug command line option,
306
--flow-size
ebook-convert-epub-output command
line option, 342
--font-size-mapping
ebook-convert command line option,
328
--for-machine
calibredb-list command line option,
314
--force
calibredb-remove_custom_column com-
mand line option, 321
--force-max-line-length
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--force-reload
ebook-viewer command line option, 355
--fork
calibre-smtp command line option, 310
--format
ebook-convert-pdb-output command
line option, 346
--formats
calibredb-export command line op-
tion, 317
--formatting-type
ebook-convert-txt-input command
line option, 340
--from-opf
ebook-convert command line option,
Index 401
calibre User Manual, Release 7.19.0
333
ebook-meta command line option, 353
--full-image-depth
ebook-convert-pml-output command
line option, 349
--full-screen
ebook-viewer command line option, 355
--fullscreen
ebook-viewer command line option, 355
--generate-authors
calibredb-catalog command line op-
tion, 319
--generate-descriptions
calibredb-catalog command line op-
tion, 319
--generate-genres
calibredb-catalog command line op-
tion, 319
--generate-recently-added
calibredb-catalog command line op-
tion, 319
--generate-series
calibredb-catalog command line op-
tion, 319
--generate-titles
calibredb-catalog command line op-
tion, 319
--genre-source-field
calibredb-catalog command line op-
tion, 319
--get-cover
ebook-meta command line option, 353
--gui
calibre-debug command line option,
306
--gui-debug
calibre-debug command line option,
306
--header
ebook-convert-lrf-output command
line option, 344
--header-format
ebook-convert-lrf-output command
line option, 344
--header-note-source-field
calibredb-catalog command line op-
tion, 319
--header-separation
ebook-convert-lrf-output command
line option, 344
--help
calibre command line option, 303
calibre-customize command line op-
tion, 304
calibre-debug command line option,
306
calibre-server command line option,
308
calibre-smtp command line option, 310
command line option, 313
ebook-convert command line option,
327
ebook-edit command line option, 352
ebook-meta command line option, 353
ebook-polish command line option, 354
ebook-viewer command line option, 355
fetch-ebook-metadata command line
option, 356
lrf2lrs command line option, 357
lrfviewer command line option, 358
lrs2lrf command line option, 358
web2disk command line option, 359
--html-unwrap-factor
ebook-convert command line option,
330
--htmlz-class-style
ebook-convert-htmlz-output command
line option, 344
--htmlz-css-type
ebook-convert-htmlz-output command
line option, 344
--htmlz-title-filename
ebook-convert-htmlz-output command
line option, 344
--identifier
calibredb-add command line option,
315
ebook-meta command line option, 353
fetch-ebook-metadata command line
option, 356
--ids
calibredb-catalog command line op-
tion, 318
--ignore
calibredb-add command line option,
315
--ignore_extensions
calibredb-check_library command
line option, 322
--ignore_names
calibredb-check_library command
line option, 322
--ignore-plugins
calibre command line option, 303
--ignore-wmf
ebook-convert-rtf-input command
line option, 339
--ignored-fields
402 Index
calibre User Manual, Release 7.19.0
calibre-server command line option,
308
--implode-book
calibre-debug command line option,
306
--import-calibre-data
calibre-debug command line option,
306
--include-snippets
calibredb-fts_search command line
option, 325
--index
ebook-meta command line option, 353
--indexing-speed
calibredb-fts_index command line
option, 324
--indexing-threshold
calibredb-fts_search command line
option, 325
--inline-toc
ebook-convert-pdb-output command
line option, 346
ebook-convert-pml-output command
line option, 349
ebook-convert-rb-output command
line option, 349
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--input-encoding
ebook-convert-azw4-input command
line option, 334
ebook-convert-chm-input command
line option, 334
ebook-convert-comic-input command
line option, 335
ebook-convert-djvu-input command
line option, 335
ebook-convert-docx-input command
line option, 336
ebook-convert-epub-input command
line option, 336
ebook-convert-fb2-input command
line option, 336
ebook-convert-htlz-input command
line option, 336
ebook-convert-html-input command
line option, 337
ebook-convert-lit-input command
line option, 337
ebook-convert-lrf-input command
line option, 337
ebook-convert-mobi-input command
line option, 337
ebook-convert-odt-input command
line option, 337
ebook-convert-pdb-input command
line option, 338
ebook-convert-pdf-input command
line option, 338
ebook-convert-pml-input command
line option, 338
ebook-convert-rb-input command line
option, 339
ebook-convert-recipe-input command
line option, 339
ebook-convert-rtf-input command
line option, 339
ebook-convert-snb-input command
line option, 340
ebook-convert-tcr-input command
line option, 340
ebook-convert-txt-input command
line option, 340
--input-profile
ebook-convert command line option,
327
--insert-blank-line
ebook-convert command line option,
328
--insert-blank-line-size
ebook-convert command line option,
328
--insert-metadata
ebook-convert command line option,
332
--inspect-mobi
calibre-debug command line option,
306
--is-multiple
calibredb-add_custom_column command
line option, 321
--isbn
calibredb-add command line option,
315
ebook-convert command line option,
333
ebook-meta command line option, 353
fetch-ebook-metadata command line
option, 356
--item_count
calibredb-list_categories command
line option, 323
--jacket
ebook-polish command line option, 354
--keep-aspect-ratio
ebook-convert-comic-input command
Index 403
calibre User Manual, Release 7.19.0
line option, 335
--keep-color
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--keep-image-references
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--keep-ligatures
ebook-convert command line option,
329
--keep-links
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--landscape
ebook-convert-comic-input command
line option, 335
--language
ebook-convert command line option,
333
ebook-meta command line option, 353
--languages
calibredb-add command line option,
315
--level1-toc
ebook-convert command line option,
332
--level2-toc
ebook-convert command line option,
332
--level3-toc
ebook-convert command line option,
332
--library-path
command line option, 313
--limit
calibredb-list command line option,
314
calibredb-search command line op-
tion, 324
--line-height
ebook-convert command line option,
329
--line-width
calibredb-list command line option,
314
--linearize-tables
ebook-convert command line option,
329
--list-fields
calibredb-set_metadata command line
option, 317
--list-plugins
calibre-customize command line op-
tion, 304
--list-recipes
ebook-convert command line option,
327
--listen-on
calibre-server command line option,
308
--localhost
calibre-smtp command line option, 310
--log
calibre-server command line option,
308
--lrf
ebook-convert-recipe-input command
line option, 339
--lrf-bookid
ebook-meta command line option, 353
--lrs
lrs2lrf command line option, 358
--manage-users
calibre-server command line option,
309
--margin-bottom
ebook-convert command line option,
329
--margin-left
ebook-convert command line option,
329
--margin-right
ebook-convert command line option,
329
--margin-top
ebook-convert command line option,
329
--markdown-extensions
ebook-convert-txt-input command
line option, 340
--match-end-marker
calibredb-fts_search command line
option, 325
--match-regexp
web2disk command line option, 359
--match-start-marker
calibredb-fts_search command line
option, 325
--max-files
web2disk command line option, 359
--max-header-line-size
404 Index
calibre User Manual, Release 7.19.0
calibre-server command line option,
309
--max-job-time
calibre-server command line option,
309
--max-jobs
calibre-server command line option,
309
--max-levels
ebook-convert-html-input command
line option, 337
--max-line-length
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--max-log-size
calibre-server command line option,
309
--max-opds-items
calibre-server command line option,
309
--max-opds-ungrouped-items
calibre-server command line option,
309
--max-recursions
web2disk command line option, 359
--max-request-body-size
calibre-server command line option,
309
--max-toc-links
ebook-convert command line option,
332
--merge-comments-rule
calibredb-catalog command line op-
tion, 319
--minimum-indent
ebook-convert-lrf-output command
line option, 345
--minimum-line-height
ebook-convert command line option,
329
--mobi-file-type
ebook-convert-mobi-output command
line option, 345
--mobi-ignore-margins
ebook-convert-mobi-output command
line option, 345
--mobi-keep-original-images
ebook-convert-mobi-output command
line option, 345
--mobi-toc-at-start
ebook-convert-azw3-output command
line option, 341
ebook-convert-mobi-output command
line option, 345
--mono-family
ebook-convert-lrf-output command
line option, 345
--new-instance
ebook-viewer command line option, 355
--new-pdf-engine
ebook-convert-pdf-input command
line option, 338
--newline
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--no-chapters-in-toc
ebook-convert command line option,
332
--no-default-epub-cover
ebook-convert-epub-output command
line option, 342
--no-images
ebook-convert-pdf-input command
line option, 338
--no-inline-fb2-toc
ebook-convert-fb2-input command
line option, 336
--no-inline-toc
ebook-convert-azw3-output command
line option, 341
ebook-convert-mobi-output command
line option, 345
--no-process
ebook-convert-comic-input command
line option, 335
--no-sort
ebook-convert-comic-input command
line option, 335
--no-svg-cover
ebook-convert-epub-output command
line option, 342
--no-update-check
calibre command line option, 303
--num-per-page
calibre-server command line option,
309
--one-book-per-directory
calibredb-add command line option,
315
--only-formats
calibredb-embed_metadata command
line option, 323
--open-at
ebook-viewer command line option, 356
Index 405
calibre User Manual, Release 7.19.0
--opf
ebook-polish command line option, 354
fetch-ebook-metadata command line
option, 356
--outbox
calibre-smtp command line option, 310
--output
lrf2lrs command line option, 357
lrs2lrf command line option, 358
--output-format
calibredb-fts_search command line
option, 325
ebook-convert-comic-input command
line option, 335
--output-profile
calibredb-catalog command line op-
tion, 319
ebook-convert command line option,
327
--page-breaks-before
ebook-convert command line option,
332
--paper-size
ebook-convert-pdf-output command
line option, 347
--paragraph-type
ebook-convert-txt-input command
line option, 340
--password
calibre-smtp command line option, 311
command line option, 313
ebook-convert-recipe-input command
line option, 339
--paths
calibre-debug command line option,
306
--pdb-output-encoding
ebook-convert-pdb-output command
line option, 346
--pdf-add-toc
ebook-convert-pdf-output command
line option, 347
--pdf-default-font-size
ebook-convert-pdf-output command
line option, 347
--pdf-footer-regex
ebook-convert-pdf-input command
line option, 338
--pdf-footer-skip
ebook-convert-pdf-input command
line option, 338
--pdf-footer-template
ebook-convert-pdf-output command
line option, 347
--pdf-header-regex
ebook-convert-pdf-input command
line option, 338
--pdf-header-skip
ebook-convert-pdf-input command
line option, 338
--pdf-header-template
ebook-convert-pdf-output command
line option, 347
--pdf-hyphenate
ebook-convert-pdf-output command
line option, 347
--pdf-mark-links
ebook-convert-pdf-output command
line option, 347
--pdf-mono-family
ebook-convert-pdf-output command
line option, 347
--pdf-mono-font-size
ebook-convert-pdf-output command
line option, 347
--pdf-no-cover
ebook-convert-pdf-output command
line option, 347
--pdf-odd-even-offset
ebook-convert-pdf-output command
line option, 347
--pdf-page-margin-bottom
ebook-convert-pdf-output command
line option, 347
--pdf-page-margin-left
ebook-convert-pdf-output command
line option, 347
--pdf-page-margin-right
ebook-convert-pdf-output command
line option, 347
--pdf-page-margin-top
ebook-convert-pdf-output command
line option, 348
--pdf-page-number-map
ebook-convert-pdf-output command
line option, 348
--pdf-page-numbers
ebook-convert-pdf-output command
line option, 348
--pdf-sans-family
ebook-convert-pdf-output command
line option, 348
--pdf-serif-family
ebook-convert-pdf-output command
line option, 348
--pdf-standard-font
ebook-convert-pdf-output command
line option, 348
406 Index
calibre User Manual, Release 7.19.0
--pdf-use-document-margins
ebook-convert-pdf-output command
line option, 348
--permanent
calibredb-remove command line op-
tion, 316
--personal-doc
ebook-convert-mobi-output command
line option, 346
--pidfile
calibre-server command line option,
309
--pml-output-encoding
ebook-convert-pml-output command
line option, 349
--port
calibre-server command line option,
309
calibre-smtp command line option, 311
--prefer-author-sort
ebook-convert-azw3-output command
line option, 341
ebook-convert-mobi-output command
line option, 346
--prefer-metadata-cover
ebook-convert command line option,
332
--prefix
calibredb-list command line option,
314
--prefix-rules
calibredb-catalog command line op-
tion, 320
--preserve-cover-aspect-ratio
ebook-convert-docx-output command
line option, 342
ebook-convert-epub-output command
line option, 343
ebook-convert-pdf-output command
line option, 348
--preserve-spaces
ebook-convert-txt-input command
line option, 340
--preset
calibredb-catalog command line op-
tion, 320
--pretty-print
ebook-convert-azw3-output command
line option, 341
ebook-convert-docx-output command
line option, 342
ebook-convert-epub-output command
line option, 343
ebook-convert-fb2-output command
line option, 343
ebook-convert-html-output command
line option, 344
ebook-convert-htmlz-output command
line option, 344
ebook-convert-lit-output command
line option, 344
ebook-convert-lrf-output command
line option, 345
ebook-convert-mobi-output command
line option, 346
ebook-convert-oeb-output command
line option, 346
ebook-convert-pdb-output command
line option, 346
ebook-convert-pdf-output command
line option, 348
ebook-convert-pml-output command
line option, 349
ebook-convert-rb-output command
line option, 349
ebook-convert-rtf-output command
line option, 349
ebook-convert-snb-output command
line option, 349
ebook-convert-tcr-output command
line option, 350
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--profile
lrfviewer command line option, 358
--progress
calibredb-export command line op-
tion, 318
--pubdate
ebook-convert command line option,
333
--publisher
ebook-convert command line option,
333
ebook-meta command line option, 353
--raise-window
ebook-viewer command line option, 356
--rating
ebook-convert command line option,
333
ebook-meta command line option, 353
--read-metadata-from-opf
ebook-convert command line option,
333
--really-do-it
calibredb-restore_database command
Index 407
calibre User Manual, Release 7.19.0
line option, 322
--recipe-specific-option
ebook-convert-recipe-input command
line option, 339
--recurse
calibredb-add command line option,
315
--relay
calibre-smtp command line option, 311
--remove-first-image
ebook-convert command line option,
332
--remove-jacket
ebook-polish command line option, 354
--remove-paragraph-spacing
ebook-convert command line option,
329
--remove-paragraph-spacing-indent-size
ebook-convert command line option,
329
--remove-plugin
calibre-customize command line op-
tion, 304
--remove-soft-hyphens
ebook-polish command line option, 354
--remove-unused-css
ebook-polish command line option, 354
--render-tables-as-images
ebook-convert-lrf-output command
line option, 345
--replace-scene-breaks
ebook-convert command line option,
331
--replace-whitespace
calibredb-export command line op-
tion, 318
--report
calibredb-check_library command
line option, 322
--restrict-to
calibredb-fts_search command line
option, 325
--right2left
ebook-convert-comic-input command
line option, 335
--run-plugin
calibre-debug command line option,
306
--run-test
calibre-debug command line option,
306
--run-without-debug
calibre-debug command line option,
306
--sans-family
ebook-convert-lrf-output command
line option, 345
--search
calibredb-catalog command line op-
tion, 318
calibredb-list command line option,
314
--search-replace
ebook-convert command line option,
331
--search-the-net-urls
calibre-server command line option,
309
--sectionize
ebook-convert-fb2-output command
line option, 343
--select-text
ebook-edit command line option, 352
--separator
calibredb-list command line option,
314
--series
calibredb-add command line option,
315
ebook-convert command line option,
333
ebook-meta command line option, 353
--series-index
calibredb-add command line option,
315
ebook-convert command line option,
333
--serif-family
ebook-convert-lrf-output command
line option, 345
--share-not-sync
ebook-convert-azw3-output command
line option, 341
ebook-convert-mobi-output command
line option, 346
--shutdown-running-calibre
calibre command line option, 304
calibre-debug command line option,
306
--shutdown-timeout
calibre-server command line option,
309
--single-dir
calibredb-export command line op-
tion, 318
--smarten-punctuation
ebook-convert command line option,
329
408 Index
calibre User Manual, Release 7.19.0
ebook-polish command line option, 355
--snb-dont-indent-first-line
ebook-convert-snb-output command
line option, 349
--snb-full-screen
ebook-convert-snb-output command
line option, 349
--snb-hide-chapter-name
ebook-convert-snb-output command
line option, 349
--snb-insert-empty-line
ebook-convert-snb-output command
line option, 349
--snb-max-line-length
ebook-convert-snb-output command
line option, 349
--snb-output-encoding
ebook-convert-snb-output command
line option, 349
--sort-by
calibredb-list command line option,
314
--sr1-replace
ebook-convert command line option,
331
--sr1-search
ebook-convert command line option,
331
--sr2-replace
ebook-convert command line option,
331
--sr2-search
ebook-convert command line option,
331
--sr3-replace
ebook-convert command line option,
331
--sr3-search
ebook-convert command line option,
331
--ssl-certfile
calibre-server command line option,
309
--ssl-keyfile
calibre-server command line option,
309
--start-in-tray
calibre command line option, 304
--start-reading-at
ebook-convert command line option,
332
--subject
calibre-smtp command line option, 311
--subset-embedded-fonts
ebook-convert command line option,
330
--subset-font
calibre-debug command line option,
306
--subset-fonts
ebook-polish command line option, 355
--tags
calibredb-add command line option,
315
ebook-convert command line option,
333
ebook-meta command line option, 353
--tcr-output-encoding
ebook-convert-tcr-output command
line option, 350
--template
calibredb-export command line op-
tion, 318
calibredb-list command line option,
314
--template_file
calibredb-list command line option,
314
--template_heading
calibredb-list command line option,
314
--template-css
ebook-convert-html-output command
line option, 344
--template-html
ebook-convert-html-output command
line option, 344
--template-html-index
ebook-convert-html-output command
line option, 344
--test
ebook-convert-recipe-input command
line option, 339
--test-build
calibre-debug command line option,
306
--text-size-multiplier-for-rendered-
tables
ebook-convert-lrf-output command
line option, 345
--thumb-width
calibredb-catalog command line op-
tion, 320
--timefmt
calibredb-export command line op-
tion, 318
--timeout
calibre-server command line option,
Index 409
calibre User Manual, Release 7.19.0
309
calibre-smtp command line option, 311
command line option, 313
fetch-ebook-metadata command line
option, 356
web2disk command line option, 359
--timestamp
ebook-convert command line option,
333
--title
calibredb-add command line option,
315
ebook-convert command line option,
334
ebook-meta command line option, 353
fetch-ebook-metadata command line
option, 357
--title-sort
ebook-convert command line option,
334
ebook-meta command line option, 353
--to-dir
calibredb-export command line op-
tion, 318
--to-lowercase
calibredb-export command line op-
tion, 318
--to-opf
ebook-meta command line option, 353
--toc-filter
ebook-convert command line option,
332
--toc-threshold
ebook-convert command line option,
333
--toc-title
ebook-convert-azw3-output command
line option, 341
ebook-convert-epub-output command
line option, 343
ebook-convert-mobi-output command
line option, 346
ebook-convert-pdf-output command
line option, 348
--transform-css-rules
ebook-convert command line option,
330
--transform-html-rules
ebook-convert command line option,
330
--trusted-ips
calibre-server command line option,
310
--txt-in-remove-indents
ebook-convert-txt-input command
line option, 340
--txt-output-encoding
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--txt-output-formatting
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
--uncompressed-pdf
ebook-convert-pdf-output command
line option, 348
--unit
ebook-convert-pdf-output command
line option, 348
--unsmarten-punctuation
ebook-convert command line option,
330
--unwrap-factor
ebook-convert-pdf-input command
line option, 338
--upgrade-book
ebook-polish command line option, 355
--url-prefix
calibre-server command line option,
310
--use-auto-toc
ebook-convert command line option,
333
--use-existing-cover
calibredb-catalog command line op-
tion, 320
--use-profile-size
ebook-convert-pdf-output command
line option, 348
--userdb
calibre-server command line option,
310
--username
calibre-smtp command line option, 311
command line option, 313
ebook-convert-recipe-input command
line option, 339
--vacuum-fts-db
calibredb-check_library command
line option, 322
--verbose
calibre command line option, 304
calibre-smtp command line option, 311
calibredb-catalog command line op-
tion, 318
410 Index
calibre User Manual, Release 7.19.0
ebook-convert command line option,
334
ebook-polish command line option, 355
fetch-ebook-metadata command line
option, 357
lrf2lrs command line option, 357
lrfviewer command line option, 358
lrs2lrf command line option, 358
web2disk command line option, 359
--version
calibre command line option, 304
calibre-customize command line op-
tion, 304
calibre-debug command line option,
306
calibre-server command line option,
310
calibre-smtp command line option, 311
command line option, 313
ebook-convert command line option,
327
ebook-edit command line option, 352
ebook-meta command line option, 353
ebook-polish command line option, 355
ebook-viewer command line option, 356
fetch-ebook-metadata command line
option, 357
lrf2lrs command line option, 357
lrfviewer command line option, 358
lrs2lrf command line option, 358
web2disk command line option, 359
--viewer
calibre-debug command line option,
307
--visual-debug
lrfviewer command line option, 358
--wait-for-completion
calibredb-fts_index command line
option, 324
--white-background
lrfviewer command line option, 358
--wide
ebook-convert-comic-input command
line option, 335
--width
calibredb-list_categories command
line option, 323
--with-library
calibre command line option, 304
command line option, 313
--wordspace
ebook-convert-lrf-output command
line option, 345
--worker-count
calibre-server command line option,
310
-a
calibre-customize command line op-
tion, 304
calibre-smtp command line option, 311
calibredb-add command line option,
314
calibredb-set_custom command line
option, 321
ebook-meta command line option, 352
fetch-ebook-metadata command line
option, 356
-b
calibre-customize command line op-
tion, 304
-c
calibre-debug command line option,
305
calibredb-add command line option,
315
calibredb-check_library command
line option, 322
calibredb-list_categories command
line option, 322
ebook-meta command line option, 352
ebook-polish command line option, 354
fetch-ebook-metadata command line
option, 356
-d
calibre-debug command line option,
305
calibredb-add command line option,
315
calibredb-custom_columns command
line option, 321
ebook-convert command line option,
334
ebook-meta command line option, 352
ebook-polish command line option, 354
fetch-ebook-metadata command line
option, 356
web2disk command line option, 359
-e
calibre-debug command line option,
305
calibre-smtp command line option, 311
calibredb-add command line option,
315
calibredb-check_library command
line option, 322
ebook-polish command line option, 354
-f
calibre-debug command line option,
Index 411
calibre User Manual, Release 7.19.0
306
calibre-smtp command line option, 310
calibredb-embed_metadata command
line option, 323
calibredb-list command line option,
313
calibredb-remove_custom_column com-
mand line option, 321
calibredb-set_metadata command line
option, 317
ebook-convert-pdb-output command
line option, 346
ebook-polish command line option, 355
ebook-viewer command line option, 355
-g
calibre-debug command line option,
306
-h
calibre command line option, 303
calibre-customize command line op-
tion, 304
calibre-debug command line option,
306
calibre-server command line option,
308
calibre-smtp command line option, 310
command line option, 313
ebook-convert command line option,
327
ebook-edit command line option, 352
ebook-meta command line option, 353
ebook-polish command line option, 354
ebook-viewer command line option, 355
fetch-ebook-metadata command line
option, 356
lrf2lrs command line option, 357
lrfviewer command line option, 358
lrs2lrf command line option, 358
web2disk command line option, 359
-i
calibre-debug command line option,
306
calibredb-add command line option,
315
calibredb-catalog command line op-
tion, 318
calibredb-list_categories command
line option, 323
ebook-meta command line option, 353
ebook-polish command line option, 354
fetch-ebook-metadata command line
option, 356
-j
ebook-polish command line option, 354
-k
ebook-meta command line option, 352
-l
calibre-customize command line op-
tion, 304
calibre-smtp command line option, 310
calibredb-add command line option,
315
calibredb-search command line op-
tion, 324
calibredb-set_metadata command line
option, 317
ebook-meta command line option, 353
-m
calibre-debug command line option,
306
calibredb-add command line option,
314
ebook-convert command line option,
333
-n
calibredb-check_library command
line option, 322
ebook-convert-txt-output command
line option, 350
ebook-convert-txtz-output command
line option, 351
web2disk command line option, 359
-o
calibre-smtp command line option, 310
ebook-polish command line option, 354
fetch-ebook-metadata command line
option, 356
lrf2lrs command line option, 357
lrs2lrf command line option, 358
-p
calibre-smtp command line option, 311
ebook-meta command line option, 353
ebook-polish command line option, 355
fetch-ebook-metadata command line
option, 356
-r
calibre-customize command line op-
tion, 304
calibre-debug command line option,
306
calibre-smtp command line option, 311
calibredb-add command line option,
315
calibredb-check_library command
line option, 322
calibredb-list_categories command
line option, 322
calibredb-restore_database command
412 Index
calibre User Manual, Release 7.19.0
line option, 322
ebook-meta command line option, 353
web2disk command line option, 359
-s
calibre command line option, 304
calibre-debug command line option,
306
calibre-smtp command line option, 311
calibredb-add command line option,
315
calibredb-catalog command line op-
tion, 318
calibredb-list command line option,
314
ebook-meta command line option, 353
-t
calibre-debug command line option,
306
calibre-smtp command line option, 311
calibredb-add command line option,
315
calibredb-list command line option,
314
ebook-meta command line option, 353
fetch-ebook-metadata command line
option, 357
web2disk command line option, 359
-u
calibre-smtp command line option, 311
ebook-convert-pdf-output command
line option, 348
ebook-polish command line option, 354
-v
calibre command line option, 304
calibre-smtp command line option, 311
calibredb-catalog command line op-
tion, 318
ebook-convert command line option,
334
fetch-ebook-metadata command line
option, 357
-w
calibre-debug command line option,
307
calibredb-list command line option,
314
calibredb-list_categories command
line option, 323
-x
calibre-debug command line option,
305
A
abort_article() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
39
abort_recipe_processing() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
39
abspath_to_name() (cali-
bre.ebooks.oeb.polish.container.Container
method), 380
accept_drag_move_event() (cali-
bre.gui2.actions.InterfaceAction method),
285
accept_enter_event() (cali-
bre.gui2.actions.InterfaceAction method),
285
accepts_drops (calibre.gui2.actions.InterfaceAction
attribute), 285
action_add_menu (cali-
bre.gui2.actions.InterfaceAction attribute),
284
action_menu_clone_qaction (cali-
bre.gui2.actions.InterfaceAction attribute),
284
action_shortcut_name (cali-
bre.gui2.actions.InterfaceAction attribute),
284
action_spec (calibre.gui2.actions.InterfaceAction at-
tribute), 284
action_type (calibre.gui2.actions.InterfaceAction at-
tribute), 285
add_annotation_to_library() (cali-
bre.devices.usbms.device.Device method),
281
add_book() (calibre.devices.interface.BookList method),
278
add_books() (calibre.db.cache.Cache method), 370
add_books_to_metadata() (cali-
bre.devices.interface.DevicePlugin class method),
275
add_books_to_metadata() (cali-
bre.devices.usbms.driver.USBMS method),
283
add_custom_book_data() (calibre.db.cache.Cache
method), 370
add_extra_files() (calibre.db.cache.Cache
method), 370
add_file() (calibre.ebooks.oeb.polish.container.Container
method), 380
add_format() (calibre.db.cache.Cache method), 370
add_listener() (calibre.db.cache.Cache method),
370
add_name_to_manifest() (cali-
bre.ebooks.oeb.polish.container.Container
method), 380
add_notes_resource() (calibre.db.cache.Cache
Index 413
calibre User Manual, Release 7.19.0
method), 371
add_or_replace_jacket() (in module cali-
bre.ebooks.oeb.polish.jacket), 385
add_properties() (cali-
bre.ebooks.oeb.polish.container.Container
method), 380
add_savepoint() (calibre.gui2.tweak_book.boss.Boss
method), 389
add_toc_thumbnail() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
39
adeify_images() (cali-
bre.web.feeds.news.BasicNewsRecipe class
method), 40
all_annotation_types() (calibre.db.cache.Cache
method), 371
all_annotation_users() (calibre.db.cache.Cache
method), 371
all_annotations() (calibre.db.cache.Cache
method), 371
all_annotations_for_book() (cali-
bre.db.cache.Cache method), 371
all_book_ids() (calibre.db.cache.Cache method),
371
all_field_for() (calibre.db.cache.Cache method),
371
all_field_ids() (calibre.db.cache.Cache method),
371
all_field_keys() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
all_field_names() (calibre.db.cache.Cache
method), 371
all_non_none_fields() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
allowed_in_menu (cali-
bre.gui2.tweak_book.plugin.Tool attribute),
387
allowed_in_toolbar (cali-
bre.gui2.tweak_book.plugin.Tool attribute),
387
annotation_count_for_book() (cali-
bre.db.cache.Cache method), 371
annotations_map_for_book() (cali-
bre.db.cache.Cache method), 371
API, 393
apply_container_update_to_gui() (cali-
bre.gui2.tweak_book.boss.Boss method), 389
apply_unique_properties() (cali-
bre.ebooks.oeb.polish.container.Container
method), 380
articles_are_obfuscated (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
44
ASK_TO_ALLOW_CONNECT (cali-
bre.devices.interface.DevicePlugin attribute),
271
author (calibre.customize.InterfaceActionBase attribute),
287
author (calibre.customize.MetadataReaderPlugin at-
tribute), 262
author (calibre.customize.MetadataWriterPlugin at-
tribute), 262
author (calibre.customize.Plugin attribute), 258
author (calibre.customize.PreferencesPlugin attribute),
287
author (calibre.devices.usbms.driver.USBMS attribute),
281
author (calibre.ebooks.metadata.sources.base.Source at-
tribute), 264
author_data() (calibre.db.cache.Cache method), 371
author_sort_from_authors() (cali-
bre.db.cache.Cache method), 371
auto_cleanup (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
44
auto_cleanup_keep (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
44
auto_repeat (calibre.gui2.actions.InterfaceAction at-
tribute), 284
auto_trim_covers (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
B
BACKLOADING_ERROR_MESSAGE (cali-
bre.devices.usbms.device.Device attribute),
279
BasicNewsRecipe (class in calibre.web.feeds.news),
39
BCD (calibre.devices.interface.DevicePlugin attribute), 270
BCD (calibre.devices.usbms.device.Device attribute), 279
book_class (calibre.devices.usbms.driver.USBMS
attribute), 282
book_created (calibre.db.cache.Cache.EventType at-
tribute), 369
book_edited (calibre.db.cache.Cache.EventType
attribute), 369
book_type (calibre.ebooks.oeb.polish.container.Container
attribute), 380
BookList (class in calibre.devices.interface), 277
booklist_class (calibre.devices.usbms.driver.USBMS
attribute), 282
books() (calibre.devices.interface.DevicePlugin method),
274
414 Index
calibre User Manual, Release 7.19.0
books() (calibre.devices.usbms.driver.USBMS method),
282
books_for_field() (calibre.db.cache.Cache
method), 371
books_in_virtual_library() (cali-
bre.db.cache.Cache method), 371
books_removed (calibre.db.cache.Cache.EventType at-
tribute), 370
boss (calibre.gui2.tweak_book.plugin.Tool property), 387
Boss (class in calibre.gui2.tweak_book.boss), 389
browser_type (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
44
BuiltinAdd (class in calibre.utils.formatter_functions),
191
BuiltinAnd (class in calibre.utils.formatter_functions),
192
BuiltinAnnotationCount (class in cali-
bre.utils.formatter_functions), 194
BuiltinApproximateFormats (class in cali-
bre.utils.formatter_functions), 195
BuiltinArguments (class in cali-
bre.utils.formatter_functions), 204
BuiltinAssign (class in cali-
bre.utils.formatter_functions), 205
BuiltinAuthorLinks (class in cali-
bre.utils.formatter_functions), 195
BuiltinAuthorSorts (class in cali-
bre.utils.formatter_functions), 195
BuiltinBookCount (class in cali-
bre.utils.formatter_functions), 209
BuiltinBooksize (class in cali-
bre.utils.formatter_functions), 195
BuiltinBookValues (class in cali-
bre.utils.formatter_functions), 209
BuiltinCapitalize (class in cali-
bre.utils.formatter_functions), 206
BuiltinCeiling (class in cali-
bre.utils.formatter_functions), 191
BuiltinCharacter (class in cali-
bre.utils.formatter_functions), 207
BuiltinCheckYesNo (class in cali-
bre.utils.formatter_functions), 199
BuiltinCmp (class in calibre.utils.formatter_functions),
206
BuiltinConnectedDeviceName (class in cali-
bre.utils.formatter_functions), 195
BuiltinConnectedDeviceUUID (class in cali-
bre.utils.formatter_functions), 196
BuiltinContains (class in cali-
bre.utils.formatter_functions), 199
BuiltinCount (class in cali-
bre.utils.formatter_functions), 201
BuiltinCurrentLibraryName (class in cali-
bre.utils.formatter_functions), 196
BuiltinCurrentLibraryPath (class in cali-
bre.utils.formatter_functions), 196
BuiltinCurrentVirtualLibraryName (class in
calibre.utils.formatter_functions), 196
BuiltinDateArithmetic (class in cali-
bre.utils.formatter_functions), 192
BuiltinDaysBetween (class in cali-
bre.utils.formatter_functions), 193
BuiltinDivide (class in cali-
bre.utils.formatter_functions), 191
BuiltinEval (class in cali-
bre.utils.formatter_functions), 205
BuiltinExtraFileModtime (class in cali-
bre.utils.formatter_functions), 209
BuiltinExtraFileNames (class in cali-
bre.utils.formatter_functions), 210
BuiltinExtraFileSize (class in cali-
bre.utils.formatter_functions), 210
BuiltinField (class in cali-
bre.utils.formatter_functions), 196
BuiltinFieldExists (class in cali-
bre.utils.formatter_functions), 199
BuiltinFinishFormatting (class in cali-
bre.utils.formatter_functions), 193
BuiltinFirstMatchingCmp (class in cali-
bre.utils.formatter_functions), 206
BuiltinFirstNonEmpty (class in cali-
bre.utils.formatter_functions), 199
BuiltinFloor (class in cali-
bre.utils.formatter_functions), 191
BuiltinFormatDate (class in cali-
bre.utils.formatter_functions), 193
BuiltinFormatDateField (class in cali-
bre.utils.formatter_functions), 194
BuiltinFormatNumber (class in cali-
bre.utils.formatter_functions), 194
BuiltinFormatsModtimes (class in cali-
bre.utils.formatter_functions), 196
BuiltinFormatsPaths (class in cali-
bre.utils.formatter_functions), 197
BuiltinFormatsSizes (class in cali-
bre.utils.formatter_functions), 197
BuiltinFractionalPart (class in cali-
bre.utils.formatter_functions), 191
BuiltinGetLink (class in cali-
bre.utils.formatter_functions), 210
BuiltinGetNote (class in cali-
bre.utils.formatter_functions), 210
BuiltinGlobals (class in cali-
bre.utils.formatter_functions), 205
BuiltinHasCover (class in cali-
bre.utils.formatter_functions), 197
BuiltinHasExtraFiles (class in cali-
Index 415
calibre User Manual, Release 7.19.0
bre.utils.formatter_functions), 210
BuiltinHasNote (class in cali-
bre.utils.formatter_functions), 210
BuiltinHumanReadable (class in cali-
bre.utils.formatter_functions), 194
BuiltinIdentifierInList (class in cali-
bre.utils.formatter_functions), 200
BuiltinIfempty (class in cali-
bre.utils.formatter_functions), 199
BuiltinInList (class in cali-
bre.utils.formatter_functions), 200
BuiltinIsDarkMode (class in cali-
bre.utils.formatter_functions), 211
BuiltinIsMarked (class in cali-
bre.utils.formatter_functions), 197
BuiltinLanguageCodes (class in cali-
bre.utils.formatter_functions), 197
BuiltinLanguageStrings (class in cali-
bre.utils.formatter_functions), 197
BuiltinListCountMatching (class in cali-
bre.utils.formatter_functions), 201
BuiltinListDifference (class in cali-
bre.utils.formatter_functions), 202
BuiltinListEquals (class in cali-
bre.utils.formatter_functions), 202
BuiltinListIntersection (class in cali-
bre.utils.formatter_functions), 202
BuiltinListitem (class in cali-
bre.utils.formatter_functions), 201
BuiltinListJoin (class in cali-
bre.utils.formatter_functions), 202
BuiltinListRe (class in cali-
bre.utils.formatter_functions), 203
BuiltinListReGroup (class in cali-
bre.utils.formatter_functions), 203
BuiltinListRemoveDuplicates (class in cali-
bre.utils.formatter_functions), 203
BuiltinListSort (class in cali-
bre.utils.formatter_functions), 203
BuiltinListSplit (class in cali-
bre.utils.formatter_functions), 203
BuiltinListUnion (class in cali-
bre.utils.formatter_functions), 203
BuiltinLookup (class in cali-
bre.utils.formatter_functions), 200
BuiltinLowercase (class in cali-
bre.utils.formatter_functions), 207
BuiltinMod (class in calibre.utils.formatter_functions),
191
BuiltinMultiply (class in cali-
bre.utils.formatter_functions), 191
BuiltinNot (class in calibre.utils.formatter_functions),
192
BuiltinOndevice (class in cali-
bre.utils.formatter_functions), 198
BuiltinOr (class in calibre.utils.formatter_functions),
192
BuiltinPrint (class in cali-
bre.utils.formatter_functions), 205
BuiltinRange (class in cali-
bre.utils.formatter_functions), 204
BuiltinRatingToStars (class in cali-
bre.utils.formatter_functions), 194
BuiltinRawField (class in cali-
bre.utils.formatter_functions), 198
BuiltinRawList (class in cali-
bre.utils.formatter_functions), 198
BuiltinRe (class in calibre.utils.formatter_functions),
207
BuiltinReGroup (class in cali-
bre.utils.formatter_functions), 207
BuiltinRound (class in cali-
bre.utils.formatter_functions), 192
BuiltinSelect (class in cali-
bre.utils.formatter_functions), 201
BuiltinSeriesSort (class in cali-
bre.utils.formatter_functions), 198
BuiltinSetGlobals (class in cali-
bre.utils.formatter_functions), 211
BuiltinShorten (class in cali-
bre.utils.formatter_functions), 208
BuiltinStrcat (class in cali-
bre.utils.formatter_functions), 208
BuiltinStrcatMax (class in cali-
bre.utils.formatter_functions), 208
BuiltinStrcmp (class in cali-
bre.utils.formatter_functions), 206
BuiltinStrcmpcase (class in cali-
bre.utils.formatter_functions), 206
BuiltinStrInList (class in cali-
bre.utils.formatter_functions), 201
BuiltinStrlen (class in cali-
bre.utils.formatter_functions), 208
BuiltinSubitems (class in cali-
bre.utils.formatter_functions), 204
BuiltinSublist (class in cali-
bre.utils.formatter_functions), 204
BuiltinSubstr (class in cali-
bre.utils.formatter_functions), 208
BuiltinSubtract (class in cali-
bre.utils.formatter_functions), 192
BuiltinSwapAroundArticles (class in cali-
bre.utils.formatter_functions), 208
BuiltinSwapAroundComma (class in cali-
bre.utils.formatter_functions), 209
BuiltinSwitch (class in cali-
bre.utils.formatter_functions), 200
BuiltinSwitchIf (class in cali-
416 Index
calibre User Manual, Release 7.19.0
bre.utils.formatter_functions), 200
BuiltinTemplate (class in cali-
bre.utils.formatter_functions), 205
BuiltinTest (class in cali-
bre.utils.formatter_functions), 199
BuiltinTitlecase (class in cali-
bre.utils.formatter_functions), 207
BuiltinToday (class in cali-
bre.utils.formatter_functions), 193
BuiltinToHex (class in cali-
bre.utils.formatter_functions), 209
BuiltinTransliterate (class in cali-
bre.utils.formatter_functions), 209
BuiltinUppercase (class in cali-
bre.utils.formatter_functions), 207
BuiltinUrlsFromIdentifiers (class in cali-
bre.utils.formatter_functions), 194
BuiltinUserCategories (class in cali-
bre.utils.formatter_functions), 198
BuiltinVirtualLibraries (class in cali-
bre.utils.formatter_functions), 198
C
Cache (class in calibre.db.cache), 369
Cache.EventType (class in calibre.db.cache), 369
cached_cover_url_is_reliable (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
calibre command line option
--detach, 303
--help, 303
--ignore-plugins, 303
--no-update-check, 303
--shutdown-running-calibre, 304
--start-in-tray, 304
--verbose, 304
--version, 304
--with-library, 304
-h, 303
-s, 304
-v, 304
calibre.customize
module, 257
calibre.customize.conversion
module, 267
calibre.db.cache
module, 369
calibre.devices.interface
module, 270
calibre.ebooks.metadata.book.base
module, 211
calibre.ebooks.metadata.sources.base
module, 264
calibre.ebooks.oeb.polish.container
module, 379
calibre.ebooks.oeb.polish.cover
module, 385
calibre.ebooks.oeb.polish.css
module, 386
calibre.ebooks.oeb.polish.jacket
module, 385
calibre.ebooks.oeb.polish.pretty
module, 384
calibre.ebooks.oeb.polish.replace
module, 384
calibre.ebooks.oeb.polish.split
module, 385
calibre.ebooks.oeb.polish.toc
module, 387
calibre.gui2.tweak_book.boss
module, 389
calibre.utils.formatter_functions
module, 190
calibre.web.feeds.news
module, 39
calibre-customize command line option
--add-plugin, 304
--build-plugin, 304
--customize-plugin, 304
--disable-plugin, 304
--enable-plugin, 304
--help, 304
--list-plugins, 304
--remove-plugin, 304
--version, 304
-a, 304
-b, 304
-h, 304
-l, 304
-r, 304
calibre-debug command line option
--add-simple-plugin, 305
--command, 305
--debug-device-driver, 305
--default-programs, 305
--diff, 305
--edit-book, 305
--exec-file, 305
--explode-book, 305
--export-all-calibre-data, 305
--fix-multiprocessing, 306
--gui, 306
--gui-debug, 306
--help, 306
--implode-book, 306
--import-calibre-data, 306
--inspect-mobi, 306
--paths, 306
Index 417
calibre User Manual, Release 7.19.0
--run-plugin, 306
--run-test, 306
--run-without-debug, 306
--shutdown-running-calibre, 306
--subset-font, 306
--test-build, 306
--version, 306
--viewer, 307
-c, 305
-d, 305
-e, 305
-f, 306
-g, 306
-h, 306
-i, 306
-m, 306
-r, 306
-s, 306
-t, 306
-w, 307
-x, 305
calibre-server command line option
--access-log, 307
--ajax-timeout, 307
--auth-mode, 307
--auto-reload, 307
--ban-after, 307
--ban-for, 307
--book-list-mode, 307
--compress-min-size, 307
--custom-list-template, 307
--daemonize, 307
--disable-allow-socket-
preallocation, 308
--disable-auth, 308
--disable-fallback-to-detected-
interface, 308
--disable-local-write, 308
--disable-log-not-found, 308
--disable-use-bonjour, 308
--disable-use-sendfile, 308
--displayed-fields, 308
--enable-allow-socket-
preallocation, 308
--enable-auth, 308
--enable-fallback-to-detected-
interface, 308
--enable-local-write, 308
--enable-log-not-found, 308
--enable-use-bonjour, 308
--enable-use-sendfile, 308
--help, 308
--ignored-fields, 308
--listen-on, 308
--log, 308
--manage-users, 309
--max-header-line-size, 309
--max-job-time, 309
--max-jobs, 309
--max-log-size, 309
--max-opds-items, 309
--max-opds-ungrouped-items, 309
--max-request-body-size, 309
--num-per-page, 309
--pidfile, 309
--port, 309
--search-the-net-urls, 309
--shutdown-timeout, 309
--ssl-certfile, 309
--ssl-keyfile, 309
--timeout, 309
--trusted-ips, 310
--url-prefix, 310
--userdb, 310
--version, 310
--worker-count, 310
-h, 308
calibre-smtp command line option
--attachment, 311
--cafile, 311
--dont-verify-server-certificate,
311
--encryption-method, 311
--fork, 310
--help, 310
--localhost, 310
--outbox, 310
--password, 311
--port, 311
--relay, 311
--subject, 311
--timeout, 311
--username, 311
--verbose, 311
--version, 311
-a, 311
-e, 311
-f, 310
-h, 310
-l, 310
-o, 310
-p, 311
-r, 311
-s, 311
-t, 311
-u, 311
-v, 311
calibredb-add command line option
418 Index
calibre User Manual, Release 7.19.0
-1, 315
-I, 315
-S, 315
-T, 315
--add, 315
--authors, 314
--automerge, 314
--cover, 315
--duplicates, 315
--empty, 315
--identifier, 315
--ignore, 315
--isbn, 315
--languages, 315
--one-book-per-directory, 315
--recurse, 315
--series, 315
--series-index, 315
--tags, 315
--title, 315
-a, 314
-c, 315
-d, 315
-e, 315
-i, 315
-l, 315
-m, 314
-r, 315
-s, 315
-t, 315
calibredb-add_custom_column command
line option
--display, 320
--is-multiple, 321
calibredb-add_format command line op-
tion
--as-extra-data-file, 316
--dont-replace, 316
calibredb-backup_metadata command line
option
--all, 323
calibredb-catalog command line option
--catalog-title, 319
--cross-reference-authors, 319
--debug-pipeline, 319
--exclude-genre, 319
--exclusion-rules, 319
--generate-authors, 319
--generate-descriptions, 319
--generate-genres, 319
--generate-recently-added, 319
--generate-series, 319
--generate-titles, 319
--genre-source-field, 319
--header-note-source-field, 319
--ids, 318
--merge-comments-rule, 319
--output-profile, 319
--prefix-rules, 320
--preset, 320
--search, 318
--thumb-width, 320
--use-existing-cover, 320
--verbose, 318
-i, 318
-s, 318
-v, 318
calibredb-check_library command line
option
--csv, 322
--ignore_extensions, 322
--ignore_names, 322
--report, 322
--vacuum-fts-db, 322
-c, 322
-e, 322
-n, 322
-r, 322
calibredb-custom_columns command line
option
--details, 321
-d, 321
calibredb-embed_metadata command line
option
--only-formats, 323
-f, 323
calibredb-export command line option
--all, 317
--dont-asciiize, 317
--dont-save-cover, 317
--dont-save-extra-files, 317
--dont-update-metadata, 317
--dont-write-opf, 317
--formats, 317
--progress, 318
--replace-whitespace, 318
--single-dir, 318
--template, 318
--timefmt, 318
--to-dir, 318
--to-lowercase, 318
calibredb-fts_index command line option
--indexing-speed, 324
--wait-for-completion, 324
calibredb-fts_search command line op-
tion
--do-not-match-on-related-words, 325
--include-snippets, 325
Index 419
calibre User Manual, Release 7.19.0
--indexing-threshold, 325
--match-end-marker, 325
--match-start-marker, 325
--output-format, 325
--restrict-to, 325
calibredb-list command line option
--ascending, 313
--fields, 313
--for-machine, 314
--limit, 314
--line-width, 314
--prefix, 314
--search, 314
--separator, 314
--sort-by, 314
--template, 314
--template_file, 314
--template_heading, 314
-f, 313
-s, 314
-t, 314
-w, 314
calibredb-list_categories command line
option
--categories, 322
--csv, 322
--dialect, 323
--item_count, 323
--width, 323
-c, 322
-i, 323
-r, 322
-w, 323
calibredb-remove command line option
--permanent, 316
calibredb-remove_custom_column command
line option
--force, 321
-f, 321
calibredb-restore_database command
line option
--really-do-it, 322
-r, 322
calibredb-search command line option
--limit, 324
-l, 324
calibredb-set_custom command line op-
tion
--append, 321
-a, 321
calibredb-set_metadata command line op-
tion
--field, 317
--list-fields, 317
-f, 317
-l, 317
calibredb-show_metadata command line
option
--as-opf, 316
can_be_disabled (cali-
bre.customize.conversion.InputFormatPlugin
attribute), 267
can_be_disabled (cali-
bre.customize.conversion.OutputFormatPlugin
attribute), 269
can_be_disabled (cali-
bre.customize.InterfaceActionBase attribute),
287
can_be_disabled (calibre.customize.Plugin attribute),
259
can_be_disabled (cali-
bre.customize.PreferencesPlugin attribute),
287
CAN_DO_DEVICE_DB_PLUGBOARD (cali-
bre.devices.interface.DevicePlugin attribute),
271
can_get_multiple_covers (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
can_handle() (calibre.devices.interface.DevicePlugin
method), 273
can_handle_windows() (cali-
bre.devices.interface.DevicePlugin method),
272
can_handle_windows() (cali-
bre.devices.usbms.device.Device method),
280
CAN_SET_METADATA (cali-
bre.devices.interface.DevicePlugin attribute),
271
CAN_SET_METADATA (cali-
bre.devices.usbms.driver.USBMS attribute),
282
canonicalize_internal_url() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
40
capabilities (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
card_prefix() (calibre.devices.interface.DevicePlugin
method), 273
card_prefix() (calibre.devices.usbms.device.Device
method), 280
CatalogPlugin (class in calibre.customize), 263
category (calibre.customize.PreferencesPlugin attribute),
288
category_order (calibre.customize.PreferencesPlugin
attribute), 287
420 Index
calibre User Manual, Release 7.19.0
center_navbar (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
44
change_font() (in module cali-
bre.ebooks.oeb.polish.fonts), 386
changed_signal (cali-
bre.gui2.preferences.CongWidgetBase attribute),
289
changed_signal (cali-
bre.gui2.preferences.CongWidgetInterface
attribute), 288
clean_downloaded_metadata() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
cleanup() (calibre.web.feeds.news.BasicNewsRecipe
method), 40
CLI (class in calibre.devices.usbms.cli), 281
cli_main() (calibre.customize.Plugin method), 260
cli_options (calibre.customize.CatalogPlugin at-
tribute), 263
clone_browser() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
40
close_editor() (calibre.gui2.tweak_book.boss.Boss
method), 389
command line option
--help, 313
--library-path, 313
--password, 313
--timeout, 313
--username, 313
--version, 313
--with-library, 313
-h, 313
commit() (calibre.ebooks.oeb.polish.container.Container
method), 380
commit() (calibre.gui2.preferences.CongWidgetBase
method), 289
commit() (calibre.gui2.preferences.CongWidgetInterface
method), 288
commit_all_editors_to_container() (cali-
bre.gui2.tweak_book.boss.Boss method), 389
commit_item() (cali-
bre.ebooks.oeb.polish.container.Container
method), 380
common_options (cali-
bre.customize.conversion.InputFormatPlugin
attribute), 268
common_options (cali-
bre.customize.conversion.OutputFormatPlugin
attribute), 269
compress_covers() (calibre.db.cache.Cache
method), 372
compress_news_images (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
44
compress_news_images_auto_size (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
45
compress_news_images_max_size (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
45
config_help_message (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
config_widget (calibre.customize.PreferencesPlugin
attribute), 287
config_widget() (calibre.customize.Plugin method),
259
config_widget() (cali-
bre.devices.interface.DevicePlugin class method),
275
config_widget() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
ConfigWidgetBase (class in calibre.gui2.preferences),
289
ConfigWidgetInterface (class in cali-
bre.gui2.preferences), 288
Container (class in calibre.ebooks.oeb.polish.container),
380
contains(), 160
conversion_options (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
45
convert() (calibre.customize.conversion.InputFormatPlugin
method), 268
convert() (calibre.customize.conversion.OutputFormatPlugin
method), 269
copy_cover_to() (calibre.db.cache.Cache method),
372
copy_format_to() (calibre.db.cache.Cache method),
372
core_usage (calibre.customize.conversion.InputFormatPlugin
attribute), 268
cover() (calibre.db.cache.Cache method), 372
cover_margins (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
45
create_action() (cali-
bre.gui2.tweak_book.plugin.Tool method),
388
create_inline_toc() (in module cali-
bre.ebooks.oeb.polish.toc), 387
create_menu_action() (cali-
bre.gui2.actions.InterfaceAction method),
285
create_widget() (cali-
Index 421
calibre User Manual, Release 7.19.0
bre.customize.PreferencesPlugin method),
288
CSS, 393
current_container (cali-
bre.gui2.tweak_book.plugin.Tool property),
387
currently_editing (cali-
bre.gui2.tweak_book.boss.Boss property),
389
custom_field_keys() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
customization_help() (calibre.customize.Plugin
method), 260
customization_help() (cali-
bre.ebooks.metadata.sources.base.Source
method), 264
D
data_for_find_identical_books() (cali-
bre.db.cache.Cache method), 372
data_for_has_book() (calibre.db.cache.Cache
method), 372
debug_managed_device_detection() (cal-
ibre.devices.interface.DevicePlugin method),
272
deepcopy() (calibre.ebooks.metadata.book.base.Metadata
method), 211
default_cover() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
40
delay (calibre.web.feeds.news.BasicNewsRecipe at-
tribute), 45
delete_annotations() (calibre.db.cache.Cache
method), 372
delete_books() (cali-
bre.devices.interface.DevicePlugin method),
275
delete_books() (calibre.devices.usbms.driver.USBMS
method), 283
delete_custom_book_data() (cali-
bre.db.cache.Cache method), 372
delete_trash_entry() (calibre.db.cache.Cache
method), 372
description (calibre.customize.conversion.OutputFormatPlugin
property), 269
description (calibre.customize.Plugin attribute), 258
description (calibre.customize.PreferencesPlugin at-
tribute), 288
description (calibre.devices.usbms.driver.USBMS at-
tribute), 281
description (calibre.web.feeds.news.BasicNewsRecipe
attribute), 45
detect_managed_devices() (cali-
bre.devices.interface.DevicePlugin method),
272
Device (class in calibre.devices.usbms.device), 279
DevicePlugin (class in calibre.devices.interface), 270
dirty() (calibre.ebooks.oeb.polish.container.Container
method), 381
do_user_config() (calibre.customize.Plugin method),
259
dont_add_to (calibre.gui2.actions.InterfaceAction at-
tribute), 285
dont_remove_from (cali-
bre.gui2.actions.InterfaceAction attribute),
285
download() (calibre.web.feeds.news.BasicNewsRecipe
method), 40
download_cover() (cali-
bre.ebooks.metadata.sources.base.Source
method), 266
drop_event() (calibre.gui2.actions.InterfaceAction
method), 285
E
ebook-convert command line option
--add-alt-text-to-img, 331
--asciiize, 328
--author-sort, 333
--authors, 333
--base-font-size, 328
--book-producer, 333
--change-justification, 328
--chapter, 331
--chapter-mark, 331
--comments, 333
--cover, 333
--debug-pipeline, 334
--disable-dehyphenate, 330
--disable-delete-blank-paragraphs,
330
--disable-fix-indents, 330
--disable-font-rescaling, 328
--disable-format-scene-breaks, 330
--disable-italicize-common-cases,
330
--disable-markup-chapter-headings,
330
--disable-remove-fake-margins, 331
--disable-renumber-headings, 330
--disable-unwrap-lines, 330
--duplicate-links-in-toc, 332
--embed-all-fonts, 328
--embed-font-family, 328
--enable-heuristics, 330
--expand-css, 328
422 Index
calibre User Manual, Release 7.19.0
--extra-css, 328
--filter-css, 328
--font-size-mapping, 328
--from-opf, 333
--help, 327
--html-unwrap-factor, 330
--input-profile, 327
--insert-blank-line, 328
--insert-blank-line-size, 328
--insert-metadata, 332
--isbn, 333
--keep-ligatures, 329
--language, 333
--level1-toc, 332
--level2-toc, 332
--level3-toc, 332
--line-height, 329
--linearize-tables, 329
--list-recipes, 327
--margin-bottom, 329
--margin-left, 329
--margin-right, 329
--margin-top, 329
--max-toc-links, 332
--minimum-line-height, 329
--no-chapters-in-toc, 332
--output-profile, 327
--page-breaks-before, 332
--prefer-metadata-cover, 332
--pubdate, 333
--publisher, 333
--rating, 333
--read-metadata-from-opf, 333
--remove-first-image, 332
--remove-paragraph-spacing, 329
--remove-paragraph-spacing-indent-
size, 329
--replace-scene-breaks, 331
--search-replace, 331
--series, 333
--series-index, 333
--smarten-punctuation, 329
--sr1-replace, 331
--sr1-search, 331
--sr2-replace, 331
--sr2-search, 331
--sr3-replace, 331
--sr3-search, 331
--start-reading-at, 332
--subset-embedded-fonts, 330
--tags, 333
--timestamp, 333
--title, 334
--title-sort, 334
--toc-filter, 332
--toc-threshold, 333
--transform-css-rules, 330
--transform-html-rules, 330
--unsmarten-punctuation, 330
--use-auto-toc, 333
--verbose, 334
--version, 327
-d, 334
-h, 327
-m, 333
-v, 334
ebook-convert-azw3-output command line
option
--dont-compress, 341
--extract-to, 341
--mobi-toc-at-start, 341
--no-inline-toc, 341
--prefer-author-sort, 341
--pretty-print, 341
--share-not-sync, 341
--toc-title, 341
ebook-convert-azw4-input command line
option
--input-encoding, 334
ebook-convert-chm-input command line
option
--input-encoding, 334
ebook-convert-comic-input command line
option
--colors, 334
--comic-image-size, 334
--despeckle, 334
--disable-trim, 334
--dont-add-comic-pages-to-toc, 334
--dont-grayscale, 335
--dont-normalize, 335
--dont-sharpen, 335
--input-encoding, 335
--keep-aspect-ratio, 335
--landscape, 335
--no-process, 335
--no-sort, 335
--output-format, 335
--right2left, 335
--wide, 335
ebook-convert-djvu-input command line
option
--input-encoding, 335
ebook-convert-docx-input command line
option
--docx-inline-subsup, 336
--docx-no-cover, 336
Index 423
calibre User Manual, Release 7.19.0
--docx-no-pagebreaks-between-notes,
336
--input-encoding, 336
ebook-convert-docx-output command line
option
--docx-custom-page-size, 341
--docx-no-cover, 341
--docx-no-toc, 341
--docx-page-margin-bottom, 341
--docx-page-margin-left, 341
--docx-page-margin-right, 341
--docx-page-margin-top, 341
--docx-page-size, 341
--extract-to, 342
--preserve-cover-aspect-ratio, 342
--pretty-print, 342
ebook-convert-epub-input command line
option
--input-encoding, 336
ebook-convert-epub-output command line
option
--dont-split-on-page-breaks, 342
--epub-flatten, 342
--epub-inline-toc, 342
--epub-max-image-size, 342
--epub-toc-at-end, 342
--epub-version, 342
--extract-to, 342
--flow-size, 342
--no-default-epub-cover, 342
--no-svg-cover, 342
--preserve-cover-aspect-ratio, 343
--pretty-print, 343
--toc-title, 343
ebook-convert-fb2-input command line
option
--input-encoding, 336
--no-inline-fb2-toc, 336
ebook-convert-fb2-output command line
option
--fb2-genre, 343
--pretty-print, 343
--sectionize, 343
ebook-convert-htlz-input command line
option
--input-encoding, 336
ebook-convert-html-input command line
option
--allow-local-files-outside-root,
336
--breadth-first, 336
--dont-package, 336
--input-encoding, 337
--max-levels, 337
ebook-convert-html-output command line
option
--extract-to, 344
--pretty-print, 344
--template-css, 344
--template-html, 344
--template-html-index, 344
ebook-convert-htmlz-output command
line option
--htmlz-class-style, 344
--htmlz-css-type, 344
--htmlz-title-filename, 344
--pretty-print, 344
ebook-convert-lit-input command line
option
--input-encoding, 337
ebook-convert-lit-output command line
option
--pretty-print, 344
ebook-convert-lrf-input command line
option
--input-encoding, 337
ebook-convert-lrf-output command line
option
--enable-autorotation, 344
--header, 344
--header-format, 344
--header-separation, 344
--minimum-indent, 345
--mono-family, 345
--pretty-print, 345
--render-tables-as-images, 345
--sans-family, 345
--serif-family, 345
--text-size-multiplier-for-
rendered-tables, 345
--wordspace, 345
ebook-convert-mobi-input command line
option
--input-encoding, 337
ebook-convert-mobi-output command line
option
--dont-compress, 345
--extract-to, 345
--mobi-file-type, 345
--mobi-ignore-margins, 345
--mobi-keep-original-images, 345
--mobi-toc-at-start, 345
--no-inline-toc, 345
--personal-doc, 346
--prefer-author-sort, 346
--pretty-print, 346
--share-not-sync, 346
--toc-title, 346
424 Index
calibre User Manual, Release 7.19.0
ebook-convert-odt-input command line
option
--input-encoding, 337
ebook-convert-oeb-output command line
option
--pretty-print, 346
ebook-convert-pdb-input command line
option
--input-encoding, 338
ebook-convert-pdb-output command line
option
--format, 346
--inline-toc, 346
--pdb-output-encoding, 346
--pretty-print, 346
-f, 346
ebook-convert-pdf-input command line
option
--input-encoding, 338
--new-pdf-engine, 338
--no-images, 338
--pdf-footer-regex, 338
--pdf-footer-skip, 338
--pdf-header-regex, 338
--pdf-header-skip, 338
--unwrap-factor, 338
ebook-convert-pdf-output command line
option
--custom-size, 347
--paper-size, 347
--pdf-add-toc, 347
--pdf-default-font-size, 347
--pdf-footer-template, 347
--pdf-header-template, 347
--pdf-hyphenate, 347
--pdf-mark-links, 347
--pdf-mono-family, 347
--pdf-mono-font-size, 347
--pdf-no-cover, 347
--pdf-odd-even-offset, 347
--pdf-page-margin-bottom, 347
--pdf-page-margin-left, 347
--pdf-page-margin-right, 347
--pdf-page-margin-top, 348
--pdf-page-number-map, 348
--pdf-page-numbers, 348
--pdf-sans-family, 348
--pdf-serif-family, 348
--pdf-standard-font, 348
--pdf-use-document-margins, 348
--preserve-cover-aspect-ratio, 348
--pretty-print, 348
--toc-title, 348
--uncompressed-pdf, 348
--unit, 348
--use-profile-size, 348
-u, 348
ebook-convert-pml-input command line
option
--input-encoding, 338
ebook-convert-pml-output command line
option
--full-image-depth, 349
--inline-toc, 349
--pml-output-encoding, 349
--pretty-print, 349
ebook-convert-rb-input command line op-
tion
--input-encoding, 339
ebook-convert-rb-output command line
option
--inline-toc, 349
--pretty-print, 349
ebook-convert-recipe-input command
line option
--dont-download-recipe, 339
--input-encoding, 339
--lrf, 339
--password, 339
--recipe-specific-option, 339
--test, 339
--username, 339
ebook-convert-rtf-input command line
option
--ignore-wmf, 339
--input-encoding, 339
ebook-convert-rtf-output command line
option
--pretty-print, 349
ebook-convert-snb-input command line
option
--input-encoding, 340
ebook-convert-snb-output command line
option
--pretty-print, 349
--snb-dont-indent-first-line, 349
--snb-full-screen, 349
--snb-hide-chapter-name, 349
--snb-insert-empty-line, 349
--snb-max-line-length, 349
--snb-output-encoding, 349
ebook-convert-tcr-input command line
option
--input-encoding, 340
ebook-convert-tcr-output command line
option
--pretty-print, 350
--tcr-output-encoding, 350
Index 425
calibre User Manual, Release 7.19.0
ebook-convert-txt-input command line
option
--formatting-type, 340
--input-encoding, 340
--markdown-extensions, 340
--paragraph-type, 340
--preserve-spaces, 340
--txt-in-remove-indents, 340
ebook-convert-txt-output command line
option
--force-max-line-length, 350
--inline-toc, 350
--keep-color, 350
--keep-image-references, 350
--keep-links, 350
--max-line-length, 350
--newline, 350
--pretty-print, 350
--txt-output-encoding, 350
--txt-output-formatting, 350
-n, 350
ebook-convert-txtz-output command line
option
--force-max-line-length, 351
--inline-toc, 351
--keep-color, 351
--keep-image-references, 351
--keep-links, 351
--max-line-length, 351
--newline, 351
--pretty-print, 351
--txt-output-encoding, 351
--txt-output-formatting, 351
-n, 351
ebook-edit command line option
--detach, 352
--help, 352
--select-text, 352
--version, 352
-h, 352
ebook-meta command line option
--author-sort, 352
--authors, 352
--book-producer, 352
--category, 352
--comments, 352
--cover, 352
--date, 352
--from-opf, 353
--get-cover, 353
--help, 353
--identifier, 353
--index, 353
--isbn, 353
--language, 353
--lrf-bookid, 353
--publisher, 353
--rating, 353
--series, 353
--tags, 353
--title, 353
--title-sort, 353
--to-opf, 353
--version, 353
-a, 352
-c, 352
-d, 352
-h, 353
-i, 353
-k, 352
-l, 353
-p, 353
-r, 353
-s, 353
-t, 353
ebook-polish command line option
-H, 354
-U, 355
--add-soft-hyphens, 354
--compress-images, 354
--cover, 354
--download-external-resources, 354
--embed-fonts, 354
--help, 354
--jacket, 354
--opf, 354
--remove-jacket, 354
--remove-soft-hyphens, 354
--remove-unused-css, 354
--smarten-punctuation, 355
--subset-fonts, 355
--upgrade-book, 355
--verbose, 355
--version, 355
-c, 354
-d, 354
-e, 354
-f, 355
-h, 354
-i, 354
-j, 354
-o, 354
-p, 355
-u, 354
ebook-viewer command line option
--continue, 355
--detach, 355
--force-reload, 355
426 Index
calibre User Manual, Release 7.19.0
--full-screen, 355
--fullscreen, 355
--help, 355
--new-instance, 355
--open-at, 356
--raise-window, 356
--version, 356
-f, 355
-h, 355
edit_file() (calibre.gui2.tweak_book.boss.Boss
method), 389
eject() (calibre.devices.interface.DevicePlugin method),
273
eject() (calibre.devices.usbms.device.Device method),
281
embed_metadata() (calibre.db.cache.Cache method),
372
encoding (calibre.web.feeds.news.BasicNewsRecipe at-
tribute), 45
exists() (calibre.ebooks.oeb.polish.container.Container
method), 381
expire_old_trash() (calibre.db.cache.Cache
method), 372
export_note() (calibre.db.cache.Cache method), 372
extra_css (calibre.web.feeds.news.BasicNewsRecipe at-
tribute), 45
extract_readable_article() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
40
F
fast_field_for() (calibre.db.cache.Cache method),
373
feeds (calibre.web.feeds.news.BasicNewsRecipe at-
tribute), 46
fetch-ebook-metadata command line op-
tion
-I, 356
--allowed-plugin, 356
--authors, 356
--cover, 356
--help, 356
--identifier, 356
--isbn, 356
--opf, 356
--timeout, 356
--title, 357
--verbose, 357
--version, 357
-a, 356
-c, 356
-d, 356
-h, 356
-i, 356
-o, 356
-p, 356
-t, 357
-v, 357
field_for() (calibre.db.cache.Cache method), 373
field_ids_for() (calibre.db.cache.Cache method),
373
field_supports_notes() (calibre.db.cache.Cache
method), 373
file_type (calibre.customize.conversion.OutputFormatPlugin
attribute), 269
file_types (calibre.customize.CatalogPlugin attribute),
263
file_types (calibre.customize.conversion.InputFormatPlugin
attribute), 267
file_types (calibre.customize.FileTypePlugin at-
tribute), 260
file_types (calibre.customize.MetadataReaderPlugin
attribute), 262
file_types (calibre.customize.MetadataWriterPlugin
attribute), 262
filename_callback() (cali-
bre.devices.usbms.device.Device method),
281
filesize() (calibre.ebooks.oeb.polish.container.Container
method), 381
FileTypePlugin (class in calibre.customize), 260
filter_css() (in module cali-
bre.ebooks.oeb.polish.css), 386
filter_regexps (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
46
find_identical_books() (calibre.db.cache.Cache
method), 373
fix_all_html() (in module cali-
bre.ebooks.oeb.polish.pretty), 384
fix_html() (in module cali-
bre.ebooks.oeb.polish.pretty), 384
for_viewer (calibre.customize.conversion.InputFormatPlugin
attribute), 268
format() (calibre.db.cache.Cache method), 373
format_abspath() (calibre.db.cache.Cache method),
373
format_added (calibre.db.cache.Cache.EventType at-
tribute), 370
format_field() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
format_hash() (calibre.db.cache.Cache method), 373
format_metadata() (calibre.db.cache.Cache
method), 373
FORMATS (calibre.devices.interface.DevicePlugin at-
tribute), 270
FORMATS (calibre.devices.usbms.driver.USBMS attribute),
Index 427
calibre User Manual, Release 7.19.0
282
formats() (calibre.db.cache.Cache method), 374
formats_removed (calibre.db.cache.Cache.EventType
attribute), 370
free_space() (calibre.devices.interface.DevicePlugin
method), 274
free_space() (calibre.devices.usbms.device.Device
method), 280
from_files() (in module cali-
bre.ebooks.oeb.polish.toc), 387
from_links() (in module cali-
bre.ebooks.oeb.polish.toc), 387
from_xpaths() (in module cali-
bre.ebooks.oeb.polish.toc), 387
G
generate_item() (cali-
bre.ebooks.oeb.polish.container.Container
method), 381
genesis() (calibre.gui2.actions.InterfaceAction
method), 286
genesis() (calibre.gui2.preferences.CongWidgetInterface
method), 288
get_all_items_that_have_notes() (cali-
bre.db.cache.Cache method), 374
get_all_link_maps_for_book() (cali-
bre.db.cache.Cache method), 374
get_all_standard_metadata() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
get_all_user_metadata() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
get_annotations() (cali-
bre.devices.usbms.device.Device method),
281
get_article_url() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
40
get_author_tokens() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
get_book_url() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
get_book_url_name() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
get_book_urls() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
get_browser() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
40
get_cached_cover_url() (cali-
bre.ebooks.metadata.sources.base.Source
method), 266
get_categories() (calibre.db.cache.Cache method),
374
get_collections() (cali-
bre.devices.interface.BookList method), 278
get_cover_url() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
41
get_custom_book_data() (calibre.db.cache.Cache
method), 374
get_device_information() (cali-
bre.devices.interface.DevicePlugin method),
273
get_device_information() (cali-
bre.devices.usbms.driver.USBMS method),
282
get_device_uid() (cali-
bre.devices.interface.DevicePlugin method),
276
get_driveinfo() (cali-
bre.devices.interface.DevicePlugin method),
273
get_extra_css() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
41
get_feeds() (calibre.web.feeds.news.BasicNewsRecipe
method), 41
get_file() (calibre.devices.interface.DevicePlugin
method), 275
get_file_path_for_processing() (cal-
ibre.ebooks.oeb.polish.container.Container
method), 381
get_id_map() (calibre.db.cache.Cache method), 374
get_identifiers() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 211
get_ids_for_custom_book_data() (cali-
bre.db.cache.Cache method), 374
get_images() (cali-
bre.customize.conversion.InputFormatPlugin
method), 268
get_item_id() (calibre.db.cache.Cache method), 374
get_item_ids() (calibre.db.cache.Cache method),
374
get_item_name() (calibre.db.cache.Cache method),
374
get_item_name_map() (calibre.db.cache.Cache
method), 375
get_link_map() (calibre.db.cache.Cache method),
375
get_masthead_title() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
428 Index
calibre User Manual, Release 7.19.0
41
get_masthead_url() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
41
get_metadata() (cali-
bre.customize.MetadataReaderPlugin method),
262
get_metadata() (calibre.db.cache.Cache method),
375
get_next_series_num_for() (cali-
bre.db.cache.Cache method), 375
get_notes_resource() (calibre.db.cache.Cache
method), 375
get_obfuscated_article() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
41
get_open_popup_message() (cali-
bre.devices.interface.DevicePlugin class method),
272
get_option() (calibre.devices.interface.DevicePlugin
method), 277
get_proxy_metadata() (calibre.db.cache.Cache
method), 375
get_recommended_folders() (in module cali-
bre.ebooks.oeb.polish.replace), 384
get_standard_metadata() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
get_title_tokens() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
get_url_specific_delay() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
41
get_usage_count_by_id() (cali-
bre.db.cache.Cache method), 375
get_user_blacklisted_devices() (cali-
bre.devices.interface.DevicePlugin method),
276
get_user_metadata() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
gui (calibre.gui2.tweak_book.plugin.Tool property), 387
gui_category (calibre.customize.PreferencesPlugin at-
tribute), 288
gui_configuration_widget() (cali-
bre.customize.conversion.InputFormatPlugin
method), 269
gui_configuration_widget() (cali-
bre.customize.conversion.OutputFormatPlugin
method), 270
gui_layout_complete() (cali-
bre.gui2.actions.InterfaceAction method),
286
gui_name (calibre.customize.PreferencesPlugin attribute),
288
guide_type_map (cali-
bre.ebooks.oeb.polish.container.Container
property), 381
H
handle_gzip (calibre.web.feeds.news.BasicNewsRecipe
attribute), 46
has_book() (calibre.db.cache.Cache method), 375
has_format() (calibre.db.cache.Cache method), 375
has_html_comments (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
has_id() (calibre.db.cache.Cache method), 375
has_name() (calibre.ebooks.oeb.polish.container.Container
method), 381
href_to_name() (cali-
bre.ebooks.oeb.polish.container.Container
method), 381
HTML, 393
I
icon (calibre.customize.PreferencesPlugin attribute), 288
icon (calibre.devices.interface.DevicePlugin attribute),
271
id_from_url() (cali-
bre.ebooks.metadata.sources.base.Source
method), 266
identify() (calibre.ebooks.metadata.sources.base.Source
method), 266
identify_results_keygen() (cali-
bre.ebooks.metadata.sources.base.Source
method), 266
ignore_connected_device() (cali-
bre.devices.interface.DevicePlugin method),
276
ignore_duplicate_articles (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
46
ignore_ssl_errors (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
image_url_processor() (cali-
bre.web.feeds.news.BasicNewsRecipe class
method), 42
import_note() (calibre.db.cache.Cache method), 375
index_to_soup() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
42
indexing_progress_changed (cali-
bre.db.cache.Cache.EventType attribute),
370
init() (calibre.db.cache.Cache method), 375
Index 429
calibre User Manual, Release 7.19.0
initial_tab_changed() (cali-
bre.gui2.preferences.CongWidgetInterface
method), 289
initialization_complete() (cali-
bre.gui2.actions.InterfaceAction method),
286
initialize() (calibre.customize.CatalogPlugin
method), 263
initialize() (calibre.customize.Plugin method), 259
initialize() (cali-
bre.gui2.preferences.CongWidgetBase method),
289
initialize() (cali-
bre.gui2.preferences.CongWidgetInterface
method), 288
InputFormatPlugin (class in cali-
bre.customize.conversion), 267
insert_into_xml() (cali-
bre.ebooks.oeb.polish.container.Container
method), 381
installation_type (calibre.customize.Plugin at-
tribute), 259
InterfaceAction (class in calibre.gui2.actions), 284
InterfaceActionBase (class in calibre.customize),
287
InternalMetadataCompareKeyGen (class in cali-
bre.ebooks.metadata.sources.base), 267
is_configured() (cali-
bre.ebooks.metadata.sources.base.Source
method), 264
is_dir (calibre.ebooks.oeb.polish.container.Container at-
tribute), 381
is_dynamically_controllable() (cali-
bre.devices.interface.DevicePlugin method),
276
is_image_collection (cali-
bre.customize.conversion.InputFormatPlugin
attribute), 267
is_link_wanted() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
42
is_null() (calibre.ebooks.metadata.book.base.Metadata
method), 211
is_running() (calibre.devices.interface.DevicePlugin
method), 277
is_usb_connected() (cali-
bre.devices.interface.DevicePlugin method),
272
items_removed (calibre.db.cache.Cache.EventType at-
tribute), 370
items_renamed (calibre.db.cache.Cache.EventType at-
tribute), 370
items_with_notes_in_book() (cali-
bre.db.cache.Cache method), 375
iterlinks() (calibre.ebooks.oeb.polish.container.Container
method), 381
K
keep_only_tags (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
46
L
language (calibre.web.feeds.news.BasicNewsRecipe at-
tribute), 46
library_about_to_change() (cali-
bre.gui2.actions.InterfaceAction method),
286
library_changed() (cali-
bre.gui2.actions.InterfaceAction method),
286
link_for() (calibre.db.cache.Cache method), 376
list_extra_files() (calibre.db.cache.Cache
method), 376
load_actual_plugin() (cali-
bre.customize.InterfaceActionBase method),
287
load_resources() (calibre.customize.Plugin method),
259
load_resources() (cali-
bre.gui2.actions.InterfaceAction method),
286
location_selected() (cali-
bre.gui2.actions.InterfaceAction method),
286
LRF, 393
lrf2lrs command line option
--dont-output-resources, 357
--help, 357
--output, 357
--verbose, 357
--version, 357
-h, 357
-o, 357
lrfviewer command line option
--disable-hyphenation, 358
--help, 358
--profile, 358
--verbose, 358
--version, 358
--visual-debug, 358
--white-background, 358
-h, 358
lrs2lrf command line option
--help, 358
--lrs, 358
--output, 358
--verbose, 358
430 Index
calibre User Manual, Release 7.19.0
--version, 358
-h, 358
-o, 358
M
make_name_unique() (cali-
bre.ebooks.oeb.polish.container.Container
method), 381
MANAGES_DEVICE_PRESENCE (cali-
bre.devices.interface.DevicePlugin attribute),
271
manifest_has_name() (cali-
bre.ebooks.oeb.polish.container.Container
method), 381
manifest_id_map (cali-
bre.ebooks.oeb.polish.container.Container
property), 381
manifest_items_of_type() (cali-
bre.ebooks.oeb.polish.container.Container
method), 381
manifest_items_with_property() (cal-
ibre.ebooks.oeb.polish.container.Container
method), 381
manifest_type_map (cali-
bre.ebooks.oeb.polish.container.Container
property), 382
mark_as_cover() (in module cali-
bre.ebooks.oeb.polish.cover), 386
mark_as_titlepage() (in module cali-
bre.ebooks.oeb.polish.cover), 386
masthead_url (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
46
match_regexps (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
46
max_articles_per_feed (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
MAX_PATH_LEN (calibre.devices.usbms.device.Device at-
tribute), 279
merge() (in module calibre.ebooks.oeb.polish.split), 385
merge_annotations_for_book() (cali-
bre.db.cache.Cache method), 376
merge_extra_files() (calibre.db.cache.Cache
method), 376
Metadata (class in calibre.ebooks.metadata.book.base),
211
metadata_changed (cali-
bre.db.cache.Cache.EventType attribute),
370
metadata_for_field() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
MetadataReaderPlugin (class in calibre.customize),
262
MetadataWriterPlugin (class in calibre.customize),
262
mi (calibre.ebooks.oeb.polish.container.Container prop-
erty), 382
minimum_calibre_version (cali-
bre.customize.Plugin attribute), 258
module
calibre.customize, 257
calibre.customize.conversion, 267
calibre.db.cache, 369
calibre.devices.interface, 270
calibre.ebooks.metadata.book.base,
211
calibre.ebooks.metadata.sources.base,
264
calibre.ebooks.oeb.polish.container,
379
calibre.ebooks.oeb.polish.cover, 385
calibre.ebooks.oeb.polish.css, 386
calibre.ebooks.oeb.polish.jacket,
385
calibre.ebooks.oeb.polish.pretty,
384
calibre.ebooks.oeb.polish.replace,
384
calibre.ebooks.oeb.polish.split, 385
calibre.ebooks.oeb.polish.toc, 387
calibre.gui2.tweak_book.boss, 389
calibre.utils.formatter_functions,
190
calibre.web.feeds.news, 39
move_book_from_trash() (calibre.db.cache.Cache
method), 376
move_format_from_trash() (cali-
bre.db.cache.Cache method), 376
multisort() (calibre.db.cache.Cache method), 376
multisplit() (in module cali-
bre.ebooks.oeb.polish.split), 385
N
name (calibre.customize.Plugin attribute), 258
name (calibre.gui2.actions.InterfaceAction attribute), 284
name (calibre.gui2.tweak_book.plugin.Tool attribute), 387
name(), 160
name_order (calibre.customize.PreferencesPlugin
attribute), 287
name_to_abspath() (cali-
bre.ebooks.oeb.polish.container.Container
method), 382
name_to_href() (cali-
bre.ebooks.oeb.polish.container.Container
method), 382
Index 431
calibre User Manual, Release 7.19.0
names_that_must_not_be_changed (cal-
ibre.ebooks.oeb.polish.container.Container
property), 382
names_that_must_not_be_removed (cal-
ibre.ebooks.oeb.polish.container.Container
property), 382
names_that_need_not_be_manifested (cal-
ibre.ebooks.oeb.polish.container.Container
property), 382
needs_subscription (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
NEWS_IN_FOLDER (calibre.devices.usbms.device.Device
attribute), 279
no_stylesheets (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
normalize_path() (cali-
bre.devices.usbms.driver.USBMS class method),
283
notes_data_for() (calibre.db.cache.Cache method),
376
notes_for() (calibre.db.cache.Cache method), 376
notes_resources_used_by() (cali-
bre.db.cache.Cache method), 376
NUKE_COMMENTS (calibre.devices.interface.DevicePlugin
attribute), 271
O
oldest_article (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
on_import (calibre.customize.FileTypePlugin attribute),
260
on_postconvert (calibre.customize.FileTypePlugin at-
tribute), 260
on_postdelete (calibre.customize.FileTypePlugin at-
tribute), 260
on_postimport (calibre.customize.FileTypePlugin at-
tribute), 260
on_postprocess (calibre.customize.FileTypePlugin at-
tribute), 260
on_preprocess (calibre.customize.FileTypePlugin at-
tribute), 260
open() (calibre.devices.interface.DevicePlugin method),
273
open() (calibre.devices.usbms.device.Device method),
281
open() (calibre.ebooks.oeb.polish.container.Container
method), 382
open_book() (calibre.gui2.tweak_book.boss.Boss
method), 389
OPEN_FEEDBACK_MESSAGE (cali-
bre.devices.interface.DevicePlugin attribute),
271
opf (calibre.ebooks.oeb.polish.container.Container prop-
erty), 382
opf_get_or_create() (cali-
bre.ebooks.oeb.polish.container.Container
method), 382
opf_version (calibre.ebooks.oeb.polish.container.Container
property), 382
opf_version_parsed (cali-
bre.ebooks.oeb.polish.container.Container
property), 382
opf_xpath() (calibre.ebooks.oeb.polish.container.Container
method), 382
options (calibre.customize.conversion.InputFormatPlugin
attribute), 268
options (calibre.customize.conversion.OutputFormatPlugin
attribute), 269
options (calibre.ebooks.metadata.sources.base.Source
attribute), 264
OSX_MAIN_MEM_VOL_PAT (cali-
bre.devices.usbms.device.Device attribute),
279
output_encoding (cali-
bre.customize.conversion.InputFormatPlugin
attribute), 268
OutputFormatPlugin (class in cali-
bre.customize.conversion), 269
P
parse_feeds() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
42
parse_index() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
42
parsed() (calibre.ebooks.oeb.polish.container.Container
method), 382
path_sep (calibre.devices.interface.DevicePlugin at-
tribute), 271
Plugin (class in calibre.customize), 258
populate_article_metadata() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
42
popup_type (calibre.gui2.actions.InterfaceAction
attribute), 284
post_yank_cleanup() (cali-
bre.devices.interface.DevicePlugin method),
273
post_yank_cleanup() (cali-
bre.devices.usbms.device.Device method),
281
postadd() (calibre.customize.FileTypePlugin method),
261
432 Index
calibre User Manual, Release 7.19.0
postconvert() (calibre.customize.FileTypePlugin
method), 261
postdelete() (calibre.customize.FileTypePlugin
method), 261
postimport() (calibre.customize.FileTypePlugin
method), 261
postprocess_book() (cali-
bre.customize.conversion.InputFormatPlugin
method), 268
postprocess_book() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
43
postprocess_html() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
43
pref() (calibre.db.cache.Cache method), 376
prefer_results_with_isbn (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
PreferencesPlugin (class in calibre.customize), 287
prepare_addable_books() (cali-
bre.devices.interface.DevicePlugin method),
276
preprocess_html() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
43
preprocess_image() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
43
preprocess_raw_html() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
43
preprocess_regexps (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
pretty_all() (in module cali-
bre.ebooks.oeb.polish.pretty), 384
pretty_css() (in module cali-
bre.ebooks.oeb.polish.pretty), 384
pretty_html() (in module cali-
bre.ebooks.oeb.polish.pretty), 384
pretty_xml() (in module cali-
bre.ebooks.oeb.polish.pretty), 384
print_version() (cali-
bre.web.feeds.news.BasicNewsRecipe class
method), 43
priority (calibre.customize.Plugin attribute), 258
priority (calibre.gui2.actions.InterfaceAction attribute),
284
PRODUCT_ID (calibre.devices.interface.DevicePlugin at-
tribute), 270
PRODUCT_ID (calibre.devices.usbms.device.Device
attribute), 279
publication_date() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
43
publication_type (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
R
raw_data() (calibre.ebooks.oeb.polish.container.Container
method), 382
re:test(), 160
read_backup() (calibre.db.cache.Cache method), 376
recipe, 393
recipe_disabled (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
recipe_specific_options (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
47
recommendations (cali-
bre.customize.conversion.InputFormatPlugin
attribute), 268
recommendations (cali-
bre.customize.conversion.OutputFormatPlugin
attribute), 269
recursions (calibre.web.feeds.news.BasicNewsRecipe
attribute), 48
refresh_gui() (cali-
bre.gui2.preferences.CongWidgetInterface
method), 289
regexp, 393
register() (calibre.gui2.preferences.CongWidgetBase
method), 289
register_shortcut() (cali-
bre.gui2.tweak_book.plugin.Tool method),
388
relpath() (calibre.ebooks.oeb.polish.container.Container
method), 383
remove_attributes (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
remove_book() (calibre.devices.interface.BookList
method), 278
remove_books() (calibre.db.cache.Cache method),
376
remove_books_from_metadata() (cali-
bre.devices.interface.DevicePlugin class method),
275
remove_books_from_metadata() (cali-
bre.devices.usbms.driver.USBMS method),
283
remove_empty_feeds (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
Index 433
calibre User Manual, Release 7.19.0
remove_formats() (calibre.db.cache.Cache method),
376
remove_from_spine() (cali-
bre.ebooks.oeb.polish.container.Container
method), 383
remove_from_xml() (cali-
bre.ebooks.oeb.polish.container.Container
method), 383
remove_item() (cali-
bre.ebooks.oeb.polish.container.Container
method), 383
remove_items() (calibre.db.cache.Cache method),
377
remove_jacket() (in module cali-
bre.ebooks.oeb.polish.jacket), 385
remove_javascript (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
remove_stale_user_metadata() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
remove_tags (calibre.web.feeds.news.BasicNewsRecipe
attribute), 48
remove_tags_after (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
remove_tags_before (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
remove_unused_css() (in module cali-
bre.ebooks.oeb.polish.css), 386
rename() (calibre.ebooks.oeb.polish.container.Container
method), 383
rename_extra_files() (calibre.db.cache.Cache
method), 377
rename_files() (in module cali-
bre.ebooks.oeb.polish.replace), 384
rename_items() (calibre.db.cache.Cache method),
377
replace() (calibre.ebooks.oeb.polish.container.Container
method), 383
replace_links() (cali-
bre.ebooks.oeb.polish.container.Container
method), 383
replace_links() (in module cali-
bre.ebooks.oeb.polish.replace), 384
requires_version (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
reset() (calibre.devices.interface.DevicePlugin method),
272
reset() (calibre.devices.usbms.device.Device method),
279
resolve_internal_links (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
restart_critical (cali-
bre.gui2.preferences.CongWidgetBase attribute),
289
restart_critical (cali-
bre.gui2.preferences.CongWidgetInterface
attribute), 288
restore_book() (calibre.db.cache.Cache method),
377
restore_defaults() (cali-
bre.gui2.preferences.CongWidgetBase method),
289
restore_defaults() (cali-
bre.gui2.preferences.CongWidgetInterface
method), 288
restore_defaults_desc (cali-
bre.gui2.preferences.CongWidgetInterface
attribute), 288
restore_original_format() (cali-
bre.db.cache.Cache method), 377
reverse_article_order (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
48
rewind_savepoint() (cali-
bre.gui2.tweak_book.boss.Boss method), 389
RSS, 393
run() (calibre.customize.CatalogPlugin method), 263
run() (calibre.customize.FileTypePlugin method), 260
S
safe_read_lock (calibre.db.cache.Cache property),
377
sanitize_callback() (cali-
bre.devices.usbms.device.Device method),
281
sanitize_path_components() (cali-
bre.devices.usbms.device.Device method),
281
save_book() (calibre.gui2.tweak_book.boss.Boss
method), 389
save_original_format()
(
calibre.db.cache.Cache
method), 377
save_settings() (calibre.customize.Plugin method),
259
save_settings() (cali-
bre.devices.interface.DevicePlugin class method),
275
save_settings() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
scale_news_images (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
49
434 Index
calibre User Manual, Release 7.19.0
scale_news_images_to_device (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
49
search() (calibre.db.cache.Cache method), 377
search_annotations() (calibre.db.cache.Cache
method), 378
search_notes() (calibre.db.cache.Cache method),
378
serialize_item() (cali-
bre.ebooks.oeb.polish.container.Container
method), 383
set_all_user_metadata() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
set_annotations_for_book() (cali-
bre.db.cache.Cache method), 378
set_conversion_options() (cali-
bre.db.cache.Cache method), 378
set_cover() (calibre.db.cache.Cache method), 378
set_cover() (in module cali-
bre.ebooks.oeb.polish.cover), 385
set_driveinfo_name() (cali-
bre.devices.interface.DevicePlugin method),
276
set_driveinfo_name() (cali-
bre.devices.usbms.driver.USBMS method),
282
set_field() (calibre.db.cache.Cache method), 378
set_identifier() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 211
set_identifiers() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 211
set_library_info() (cali-
bre.devices.interface.DevicePlugin method),
276
set_link_map() (calibre.db.cache.Cache method),
378
set_metadata() (cali-
bre.customize.MetadataWriterPlugin method),
263
set_metadata() (calibre.db.cache.Cache method),
378
set_modified() (calibre.gui2.tweak_book.boss.Boss
method), 389
set_notes_for() (calibre.db.cache.Cache method),
379
set_option() (calibre.devices.interface.DevicePlugin
method), 277
set_plugboards() (cali-
bre.devices.interface.DevicePlugin method),
275
set_pref() (calibre.db.cache.Cache method), 379
set_progress_reporter() (cali-
bre.devices.interface.DevicePlugin method),
273
set_progress_reporter() (cali-
bre.devices.usbms.device.Device method),
280
set_spine() (calibre.ebooks.oeb.polish.container.Container
method), 383
set_user_blacklisted_devices() (cali-
bre.devices.interface.DevicePlugin method),
276
set_user_metadata() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
settings() (calibre.devices.interface.DevicePlugin
class method), 275
show_current_diff() (cali-
bre.gui2.tweak_book.boss.Boss method), 389
show_editor() (calibre.gui2.tweak_book.boss.Boss
method), 390
shutdown() (calibre.devices.interface.DevicePlugin
method), 276
shutting_down() (cali-
bre.gui2.actions.InterfaceAction method),
287
simultaneous_downloads (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
49
skip_ad_pages() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
44
SLOW_DRIVEINFO (cali-
bre.devices.interface.DevicePlugin attribute),
271
smart_update() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
sort_index_by() (cali-
bre.web.feeds.news.BasicNewsRecipe method),
44
Source (class in calibre.ebooks.metadata.sources.base),
264
specialize() (cali-
bre.customize.conversion.InputFormatPlugin
method), 268
specialize_css_for_output() (cali-
bre.customize.conversion.OutputFormatPlugin
method), 270
specialize_global_preferences() (cali-
bre.devices.interface.DevicePlugin method),
276
specialize_options() (cali-
bre.customize.conversion.OutputFormatPlugin
method), 270
Index 435
calibre User Manual, Release 7.19.0
spine_items (calibre.ebooks.oeb.polish.container.Container
property), 383
spine_iter (calibre.ebooks.oeb.polish.container.Container
property), 383
spine_names (calibre.ebooks.oeb.polish.container.Container
property), 383
split() (in module calibre.ebooks.oeb.polish.split), 385
split_if_is_multiple_composite() (cali-
bre.db.cache.Cache method), 379
split_jobs() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
standard_field_keys() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
STANDARD_METADATA_FIELDS (in module cali-
bre.ebooks.metadata.book.base), 212
start_plugin() (cali-
bre.devices.interface.DevicePlugin method),
276
startup() (calibre.devices.interface.DevicePlugin
method), 276
stop_plugin() (calibre.devices.interface.DevicePlugin
method), 277
summary_length (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
49
supported_platforms (cali-
bre.customize.conversion.InputFormatPlugin
attribute), 267
supported_platforms (cali-
bre.customize.conversion.OutputFormatPlugin
attribute), 269
supported_platforms (cali-
bre.customize.InterfaceActionBase attribute),
287
supported_platforms (cali-
bre.customize.MetadataReaderPlugin attribute),
262
supported_platforms (cali-
bre.customize.MetadataWriterPlugin attribute),
262
supported_platforms (calibre.customize.Plugin at-
tribute), 258
supported_platforms (cali-
bre.customize.PreferencesPlugin attribute),
287
supported_platforms (cali-
bre.devices.usbms.driver.USBMS attribute),
282
supported_platforms (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
supports_collections() (cali-
bre.devices.interface.BookList method), 278
supports_gzip_transfer_encoding (cal-
ibre.ebooks.metadata.sources.base.Source
attribute), 264
supports_restoring_to_defaults (cali-
bre.gui2.preferences.CongWidgetBase attribute),
289
supports_restoring_to_defaults (cali-
bre.gui2.preferences.CongWidgetInterface
attribute), 288
sync_booklists() (cali-
bre.devices.interface.DevicePlugin method),
275
sync_booklists() (cali-
bre.devices.usbms.driver.USBMS method),
283
sync_preview_to_editor() (cali-
bre.gui2.tweak_book.boss.Boss method), 390
synchronize_with_db() (cali-
bre.devices.interface.DevicePlugin method),
277
T
tag_browser_context_action() (cali-
bre.gui2.actions.InterfaceAction method),
286
tag_to_string() (cali-
bre.web.feeds.news.BasicNewsRecipe class
method), 44
tags_older_than() (calibre.db.cache.Cache
method), 379
template_css (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
49
template_to_attribute() (cali-
bre.ebooks.metadata.book.base.Metadata
method), 212
temporary_file() (calibre.customize.Plugin method),
260
test_fields() (cali-
bre.ebooks.metadata.sources.base.Source
method), 265
THUMBNAIL_COMPRESSION_QUALITY (cali-
bre.devices.interface.DevicePlugin attribute),
270
THUMBNAIL_HEIGHT (cali-
bre.devices.interface.DevicePlugin attribute),
270
timefmt (calibre.web.feeds.news.BasicNewsRecipe
attribute), 49
timeout (calibre.web.feeds.news.BasicNewsRecipe
attribute), 49
title (calibre.web.feeds.news.BasicNewsRecipe at-
tribute), 49
436 Index
calibre User Manual, Release 7.19.0
to_html() (calibre.ebooks.metadata.book.base.Metadata
method), 212
Tool (class in calibre.gui2.tweak_book.plugin), 387
toolbar_button_popup_mode (cali-
bre.gui2.tweak_book.plugin.Tool attribute),
387
total_space() (calibre.devices.interface.DevicePlugin
method), 274
total_space() (calibre.devices.usbms.device.Device
method), 280
touched_fields (cali-
bre.ebooks.metadata.sources.base.Source at-
tribute), 264
type (calibre.customize.CatalogPlugin attribute), 263
type (calibre.customize.conversion.InputFormatPlugin at-
tribute), 267
type (calibre.customize.conversion.OutputFormatPlugin
attribute), 269
type (calibre.customize.FileTypePlugin attribute), 260
type (calibre.customize.InterfaceActionBase attribute),
287
type (calibre.customize.MetadataReaderPlugin attribute),
262
type (calibre.customize.MetadataWriterPlugin attribute),
262
type (calibre.customize.Plugin attribute), 259
type (calibre.customize.PreferencesPlugin attribute), 287
type (calibre.devices.interface.DevicePlugin attribute),
270
type (calibre.ebooks.metadata.sources.base.Source
attribute), 264
U
unretire_note_for() (calibre.db.cache.Cache
method), 379
update_annotations() (calibre.db.cache.Cache
method), 379
upload_books() (cali-
bre.devices.interface.DevicePlugin method),
274
upload_books() (calibre.devices.usbms.driver.USBMS
method), 282
upload_cover() (calibre.devices.usbms.driver.USBMS
method), 283
URL, 393
USBMS (class in calibre.devices.usbms.driver), 281
use_embedded_content (cali-
bre.web.feeds.news.BasicNewsRecipe attribute),
49
user_categories_for_books() (cali-
bre.db.cache.Cache method), 379
user_feedback_after_callback (cali-
bre.devices.interface.DevicePlugin attribute),
271
UserAnnotation (cali-
bre.devices.interface.DevicePlugin attribute),
271
V
VENDOR_ID (calibre.devices.interface.DevicePlugin
attribute), 270
VENDOR_ID (calibre.devices.usbms.device.Device at-
tribute), 279
version (calibre.customize.MetadataReaderPlugin
attribute), 262
version (calibre.customize.MetadataWriterPlugin
attribute), 262
version (calibre.customize.Plugin attribute), 258
VIRTUAL_BOOK_EXTENSION_MESSAGE (cali-
bre.devices.interface.DevicePlugin attribute),
271
VIRTUAL_BOOK_EXTENSIONS (cali-
bre.devices.interface.DevicePlugin attribute),
271
W
WANTS_UPDATED_THUMBNAILS (cali-
bre.devices.interface.DevicePlugin attribute),
271
web2disk command line option
--base-dir, 359
--delay, 359
--dont-download-stylesheets, 359
--encoding, 359
--filter-regexp, 359
--help, 359
--match-regexp, 359
--max-files, 359
--max-recursions, 359
--timeout, 359
--verbose, 359
--version, 359
-d, 359
-h, 359
-n, 359
-r, 359
-t, 359
WINDOWS_CARD_A_MEM (cali-
bre.devices.usbms.device.Device attribute),
279
WINDOWS_CARD_B_MEM (cali-
bre.devices.usbms.device.Device attribute),
279
WINDOWS_MAIN_MEM (cali-
bre.devices.usbms.device.Device attribute),
279
windows_sort_drives() (cali-
bre.devices.usbms.device.Device method),
Index 437
calibre User Manual, Release 7.19.0
280
438 Index