1
0
mirror of https://github.com/gryf/ebook-converter.git synced 2026-04-03 02:53:32 +02:00

Removed gettext related functions

This commit is contained in:
2020-05-03 19:00:20 +02:00
parent 35445cb736
commit 212cb56d42
92 changed files with 1505 additions and 1605 deletions

View File

@@ -16,10 +16,6 @@ from ebook_converter.utils.config_base import (
from ebook_converter.utils.lock import ExclusiveFile
# optparse uses gettext.gettext instead of _ from builtins, so we
# monkey patch it.
optparse._ = _
if False:
# Make pyflakes happy
Config, ConfigProxy, Option, OptionValues, StringConfig, OptionSet,
@@ -38,7 +34,7 @@ class CustomHelpFormatter(optparse.IndentedHelpFormatter):
if parts:
parts[0] = colored(parts[0], fg='yellow', bold=True)
usage = ' '.join(parts)
return colored(_('Usage'), fg='blue', bold=True) + ': ' + usage
return colored('Usage', fg='blue', bold=True) + ': ' + usage
def format_heading(self, heading):
from ebook_converter.utils.terminal import colored
@@ -89,21 +85,18 @@ class OptionParser(optparse.OptionParser):
usage = textwrap.dedent(usage)
if epilog is None:
epilog = _('Created by ')+colored(__author__, fg='cyan')
usage += '\n\n'+_('''Whenever you pass arguments to %prog that have spaces in them, '''
'''enclose the arguments in quotation marks. For example: "{}"''').format(
"C:\\some path with spaces" if iswindows else '/some path/with spaces') +'\n'
epilog = 'Created by ' + colored(__author__, fg='cyan')
usage += ('\n\nWhenever you pass arguments to %prog that have spaces '
'in them, enclose the arguments in quotation marks. For '
'example: "{}"\n\n').format("C:\\some path with spaces"
if iswindows
else '/some path/with spaces')
if version is None:
version = '%%prog (%s %s)'%(__appname__, get_version())
optparse.OptionParser.__init__(self, usage=usage, version=version, epilog=epilog,
formatter=CustomHelpFormatter(),
conflict_handler=conflict_handler, **kwds)
self.gui_mode = gui_mode
if False:
# Translatable string from optparse
_("Options")
_("show this help message and exit")
_("show program's version number and exit")
def print_usage(self, file=None):
from ebook_converter.utils.terminal import ANSIStream

View File

@@ -473,72 +473,70 @@ def create_global_prefs(conf_obj=None):
c = Config('global', 'calibre wide preferences') if conf_obj is None else conf_obj
c.add_opt('database_path',
default=os.path.expanduser('~/library1.db'),
help=_('Path to the database in which books are stored'))
help='Path to the database in which books are stored')
c.add_opt('filename_pattern', default=u'(?P<title>.+) - (?P<author>[^_]+)',
help=_('Pattern to guess metadata from filenames'))
help='Pattern to guess metadata from filenames')
c.add_opt('isbndb_com_key', default='',
help=_('Access key for isbndb.com'))
help='Access key for isbndb.com')
c.add_opt('network_timeout', default=5,
help=_('Default timeout for network operations (seconds)'))
help='Default timeout for network operations (seconds)')
c.add_opt('library_path', default=None,
help=_('Path to directory in which your library of books is stored'))
help='Path to directory in which your library of books is stored')
c.add_opt('language', default=None,
help=_('The language in which to display the user interface'))
help='The language in which to display the user interface')
c.add_opt('output_format', default='EPUB',
help=_('The default output format for e-book conversions. When auto-converting'
' to send to a device this can be overridden by individual device preferences.'
' These can be changed by right clicking the device icon in calibre and'
' choosing "Configure".'))
help='The default output format for e-book conversions. When auto-converting'
' to send to a device this can be overridden by individual device preferences.'
' These can be changed by right clicking the device icon in calibre and'
' choosing "Configure".')
c.add_opt('input_format_order', default=['EPUB', 'AZW3', 'MOBI', 'LIT', 'PRC',
'FB2', 'HTML', 'HTM', 'XHTM', 'SHTML', 'XHTML', 'ZIP', 'DOCX', 'ODT', 'RTF', 'PDF',
'TXT'],
help=_('Ordered list of formats to prefer for input.'))
help='Ordered list of formats to prefer for input.')
c.add_opt('read_file_metadata', default=True,
help=_('Read metadata from files'))
help='Read metadata from files')
c.add_opt('worker_process_priority', default='normal',
help=_('The priority of worker processes. A higher priority '
'means they run faster and consume more resources. '
'Most tasks like conversion/news download/adding books/etc. '
'are affected by this setting.'))
help='The priority of worker processes. A higher priority '
'means they run faster and consume more resources. '
'Most tasks like conversion/news download/adding books/etc. '
'are affected by this setting.')
c.add_opt('swap_author_names', default=False,
help=_('Swap author first and last names when reading metadata'))
help='Swap author first and last names when reading metadata')
c.add_opt('add_formats_to_existing', default=False,
help=_('Add new formats to existing book records'))
help='Add new formats to existing book records')
c.add_opt('check_for_dupes_on_ctl', default=False,
help=_('Check for duplicates when copying to another library'))
help='Check for duplicates when copying to another library')
c.add_opt('installation_uuid', default=None, help='Installation UUID')
c.add_opt('new_book_tags', default=[], help=_('Tags to apply to books added to the library'))
c.add_opt('mark_new_books', default=False, help=_(
'Mark newly added books. The mark is a temporary mark that is automatically removed when calibre is restarted.'))
c.add_opt('new_book_tags', default=[], help='Tags to apply to books added to the library')
c.add_opt('mark_new_books', default=False, help='Mark newly added books. The mark is a temporary mark that is automatically removed when calibre is restarted.')
# these are here instead of the gui preferences because calibredb and
# calibre server can execute searches
c.add_opt('saved_searches', default={}, help=_('List of named saved searches'))
c.add_opt('user_categories', default={}, help=_('User-created Tag browser categories'))
c.add_opt('saved_searches', default={}, help='List of named saved searches')
c.add_opt('user_categories', default={}, help='User-created Tag browser categories')
c.add_opt('manage_device_metadata', default='manual',
help=_('How and when calibre updates metadata on the device.'))
help='How and when calibre updates metadata on the device.')
c.add_opt('limit_search_columns', default=False,
help=_('When searching for text without using lookup '
'prefixes, as for example, Red instead of title:Red, '
'limit the columns searched to those named below.'))
help='When searching for text without using lookup '
'prefixes, as for example, Red instead of title:Red, '
'limit the columns searched to those named below.')
c.add_opt('limit_search_columns_to',
default=['title', 'authors', 'tags', 'series', 'publisher'],
help=_('Choose columns to be searched when not using prefixes, '
'as for example, when searching for Red instead of '
'title:Red. Enter a list of search/lookup names '
'separated by commas. Only takes effect if you set the option '
'to limit search columns above.'))
help='Choose columns to be searched when not using prefixes, '
'as for example, when searching for Red instead of '
'title:Red. Enter a list of search/lookup names '
'separated by commas. Only takes effect if you set the option '
'to limit search columns above.')
c.add_opt('use_primary_find_in_search', default=True,
help=_(u'Characters typed in the search box will match their '
'accented versions, based on the language you have chosen '
'for the calibre interface. For example, in '
u'English, searching for n will match both {} and n, but if '
'your language is Spanish it will only match n. Note that '
'this is much slower than a simple search on very large '
'libraries. Also, this option will have no effect if you turn '
'on case-sensitive searching'))
c.add_opt('case_sensitive', default=False, help=_(
'Make searches case-sensitive'))
help=u'Characters typed in the search box will match their '
'accented versions, based on the language you have chosen '
'for the calibre interface. For example, in '
u'English, searching for n will match both {} and n, but if '
'your language is Spanish it will only match n. Note that '
'this is much slower than a simple search on very large '
'libraries. Also, this option will have no effect if you turn '
'on case-sensitive searching')
c.add_opt('case_sensitive', default=False, help='Make searches case-sensitive')
c.add_opt('migrated', default=False, help='For Internal use. Don\'t modify.')
return c

View File

@@ -402,7 +402,7 @@ class WindowsAtomicFolderMove(object):
self.close_handles()
if getattr(e, 'winerror', 0) == winerror.ERROR_SHARING_VIOLATION:
err = IOError(errno.EACCES,
_('File is open in another process'))
'File is open in another process')
err.filename = f
raise err
prints('CreateFile failed for: %r' % f)

View File

@@ -30,7 +30,8 @@ class _Parser(object):
self.prog = prog[0]
self.prog_len = len(self.prog)
if prog[1] != '':
self.error(_('failed to scan program. Invalid input {0}').format(prog[1]))
self.error('failed to scan program. Invalid input '
'{0}'.format(prog[1]))
self.parent = parent
self.parent_kwargs = parent.kwargs
self.parent_book = parent.book
@@ -38,13 +39,13 @@ class _Parser(object):
self.funcs = funcs
def error(self, message):
m = 'Formatter: ' + message + _(' near ')
m = 'Formatter: ' + message + ' near '
if self.lex_pos > 0:
m = '{0} {1}'.format(m, self.prog[self.lex_pos-1][1])
elif self.lex_pos < self.prog_len:
m = '{0} {1}'.format(m, self.prog[self.lex_pos+1][1])
else:
m = '{0} {1}'.format(m, _('end of program'))
m = '{0} {1}'.format(m, 'end of program')
raise ValueError(m)
def token(self):
@@ -106,7 +107,7 @@ class _Parser(object):
def program(self):
val = self.statement()
if not self.token_is_eof():
self.error(_('syntax error - program ends before EOF'))
self.error('syntax error - program ends before EOF')
return val
def statement(self):
@@ -133,14 +134,14 @@ class _Parser(object):
self.parent_book, self.locals, id, self.expr())
val = self.locals.get(id, None)
if val is None:
self.error(_('Unknown identifier ') + id)
self.error('Unknown identifier ' + id)
return val
# We have a function.
# Check if it is a known one. We do this here so error reporting is
# better, as it can identify the tokens near the problem.
id = id.strip()
if id not in self.funcs:
self.error(_('unknown function {0}').format(id))
self.error('unknown function {0}'.format(id))
# Eat the paren
self.consume()
@@ -160,7 +161,7 @@ class _Parser(object):
break
self.consume()
if self.token() != ')':
self.error(_('missing closing parenthesis'))
self.error('missing closing parenthesis')
# Evaluate the function
cls = self.funcs[id]
@@ -172,7 +173,7 @@ class _Parser(object):
# String or number
return self.token()
else:
self.error(_('expression is not function or constant'))
self.error('expression is not function or constant')
class TemplateFormatter(string.Formatter):
@@ -206,14 +207,14 @@ class TemplateFormatter(string.Formatter):
try:
val = int(val)
except Exception:
raise ValueError(
_('format: type {0} requires an integer value, got {1}').format(typ, val))
raise ValueError('format: type {0} requires an integer value, '
'got {1}'.format(typ, val))
elif 'eEfFgGn%'.find(typ) >= 0:
try:
val = float(val)
except:
raise ValueError(
_('format: type {0} requires a decimal (float) value, got {1}').format(typ, val))
raise ValueError('format: type {0} requires a decimal (float) '
'value, got {1}'.format(typ, val))
return str(('{0:'+fmt+'}').format(val))
def _explode_format_string(self, fmt):
@@ -329,7 +330,7 @@ class TemplateFormatter(string.Formatter):
if self.strip_results:
val = val.strip()
else:
return _('%s: unknown function')%fname
return '%s: unknown function' % fname
if val:
val = self._do_format(val, dispfmt)
if not val:
@@ -408,7 +409,7 @@ class EvalFormatter(TemplateFormatter):
if key == '':
return ''
key = key.lower()
return kwargs.get(key, _('No such variable ') + key)
return kwargs.get(key, 'No such variable ' + key)
# DEPRECATED. This is not thread safe. Do not use.

View File

@@ -23,10 +23,10 @@ __docformat__ = 'restructuredtext en'
class FormatterFunctions(object):
error_function_body = ('def evaluate(self, formatter, kwargs, mi, locals):\n'
'\treturn "' +
_('Duplicate user function name {0}. '
'Change the name or ensure that the functions are identical') + '"')
error_function_body = ('def evaluate(self, formatter, kwargs, mi, '
'locals):\n\treturn "Duplicate user function name '
'{0}. Change the name or ensure that the functions '
'are identical"')
def __init__(self):
self._builtins = {}
@@ -39,7 +39,7 @@ class FormatterFunctions(object):
func_class.__class__.__name__))
name = func_class.name
if name in self._functions:
raise ValueError('Name %s already used'%name)
raise ValueError('Name %s already used' % name)
self._builtins[name] = func_class
self._functions[name] = func_class
for a in func_class.aliases:
@@ -51,7 +51,7 @@ class FormatterFunctions(object):
func_class.__class__.__name__))
name = func_class.name
if not replace and name in self._functions:
raise ValueError('Name %s already used'%name)
raise ValueError('Name %s already used' % name)
self._functions[name] = func_class
def register_functions(self, library_uuid, funcs):
@@ -116,7 +116,7 @@ def formatter_functions():
class FormatterFunction(object):
doc = _('No documentation provided')
doc = 'No documentation provided'
name = 'no name provided'
category = 'Unknown'
arg_count = 0
@@ -152,9 +152,9 @@ class BuiltinStrcmp(BuiltinFormatterFunction):
name = 'strcmp'
arg_count = 5
category = 'Relational'
__doc__ = doc = _('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.')
__doc__ = doc = ('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.')
def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):
v = strcmp(x, y)
@@ -169,8 +169,9 @@ class BuiltinCmp(BuiltinFormatterFunction):
name = 'cmp'
category = 'Relational'
arg_count = 5
__doc__ = doc = _('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.')
__doc__ = doc = ('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.')
def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):
x = float(x if x and x != 'None' else 0)
@@ -186,16 +187,18 @@ class BuiltinFirstMatchingCmp(BuiltinFormatterFunction):
name = 'first_matching_cmp'
category = 'Relational'
arg_count = -1
__doc__ = doc = _('first_matching_cmp(val, cmp1, result1, cmp2, r2, ..., else_result) -- '
'compares "val < cmpN" in sequence, returning resultN for '
'the first comparison that succeeds. Returns else_result '
'if no comparison succeeds. Example: '
'first_matching_cmp(10,5,"small",10,"middle",15,"large","giant") '
'returns "large". The same example with a first value of 16 returns "giant".')
__doc__ = doc = ('first_matching_cmp(val, cmp1, result1, cmp2, r2, ..., '
'else_result) -- compares "val < cmpN" in sequence, '
'returning resultN for the first comparison that '
'succeeds. Returns else_result if no comparison '
'succeeds. Example: first_matching_cmp(10,5,"small",10,'
'"middle",15,"large","giant") returns "large". The same '
'example with a first value of 16 returns "giant".')
def evaluate(self, formatter, kwargs, mi, locals, *args):
if (len(args) % 2) != 0:
raise ValueError(_('first_matching_cmp requires an even number of arguments'))
raise ValueError('first_matching_cmp requires an even number of '
'arguments')
val = float(args[0] if args[0] and args[0] != 'None' else 0)
for i in range(1, len(args) - 1, 2):
c = float(args[i] if args[i] and args[i] != 'None' else 0)
@@ -208,7 +211,7 @@ class BuiltinStrcat(BuiltinFormatterFunction):
name = 'strcat'
arg_count = -1
category = 'String manipulation'
__doc__ = doc = _('strcat(a, b, ...) -- can take any number of arguments. Returns a '
__doc__ = doc = ('strcat(a, b, ...) -- can take any number of arguments. Returns a '
'string formed by concatenating all the arguments')
def evaluate(self, formatter, kwargs, mi, locals, *args):
@@ -223,7 +226,7 @@ class BuiltinStrlen(BuiltinFormatterFunction):
name = 'strlen'
arg_count = 1
category = 'String manipulation'
__doc__ = doc = _('strlen(a) -- Returns the length of the string passed as '
__doc__ = doc = ('strlen(a) -- Returns the length of the string passed as '
'the argument')
def evaluate(self, formatter, kwargs, mi, locals, a):
@@ -237,7 +240,7 @@ class BuiltinAdd(BuiltinFormatterFunction):
name = 'add'
arg_count = 2
category = 'Arithmetic'
__doc__ = doc = _('add(x, y) -- returns x + y. Throws an exception if either x or y are not numbers.')
__doc__ = doc = 'add(x, y) -- returns x + y. Throws an exception if either x or y are not numbers.'
def evaluate(self, formatter, kwargs, mi, locals, x, y):
x = float(x if x and x != 'None' else 0)
@@ -249,7 +252,7 @@ class BuiltinSubtract(BuiltinFormatterFunction):
name = 'subtract'
arg_count = 2
category = 'Arithmetic'
__doc__ = doc = _('subtract(x, y) -- returns x - y. Throws an exception if either x or y are not numbers.')
__doc__ = doc = 'subtract(x, y) -- returns x - y. Throws an exception if either x or y are not numbers.'
def evaluate(self, formatter, kwargs, mi, locals, x, y):
x = float(x if x and x != 'None' else 0)
@@ -261,7 +264,7 @@ class BuiltinMultiply(BuiltinFormatterFunction):
name = 'multiply'
arg_count = 2
category = 'Arithmetic'
__doc__ = doc = _('multiply(x, y) -- returns x * y. Throws an exception if either x or y are not numbers.')
__doc__ = doc = 'multiply(x, y) -- returns x * y. Throws an exception if either x or y are not numbers.'
def evaluate(self, formatter, kwargs, mi, locals, x, y):
x = float(x if x and x != 'None' else 0)
@@ -273,7 +276,7 @@ class BuiltinDivide(BuiltinFormatterFunction):
name = 'divide'
arg_count = 2
category = 'Arithmetic'
__doc__ = doc = _('divide(x, y) -- returns x / y. Throws an exception if either x or y are not numbers.')
__doc__ = doc = 'divide(x, y) -- returns x / y. Throws an exception if either x or y are not numbers.'
def evaluate(self, formatter, kwargs, mi, locals, x, y):
x = float(x if x and x != 'None' else 0)
@@ -286,7 +289,7 @@ class BuiltinTemplate(BuiltinFormatterFunction):
arg_count = 1
category = 'Recursion'
__doc__ = doc = _('template(x) -- evaluates x as a template. The evaluation is done '
__doc__ = doc = ('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 '
@@ -305,7 +308,7 @@ class BuiltinEval(BuiltinFormatterFunction):
name = 'eval'
arg_count = 1
category = 'Recursion'
__doc__ = doc = _('eval(template) -- evaluates the template, passing the local '
__doc__ = doc = ('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 } '
@@ -325,7 +328,7 @@ class BuiltinAssign(BuiltinFormatterFunction):
name = 'assign'
arg_count = 2
category = 'Other'
__doc__ = doc = _('assign(id, val) -- assigns val to id, then returns val. '
__doc__ = doc = ('assign(id, val) -- assigns val to id, then returns val. '
'id must be an identifier, not an expression')
def evaluate(self, formatter, kwargs, mi, locals, target, value):
@@ -337,7 +340,7 @@ class BuiltinPrint(BuiltinFormatterFunction):
name = 'print'
arg_count = -1
category = 'Other'
__doc__ = doc = _('print(a, b, ...) -- prints the arguments to standard output. '
__doc__ = doc = ('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.')
@@ -350,7 +353,7 @@ class BuiltinField(BuiltinFormatterFunction):
name = 'field'
arg_count = 1
category = 'Get values from metadata'
__doc__ = doc = _('field(name) -- returns the metadata field named by name')
__doc__ = doc = ('field(name) -- returns the metadata field named by name')
def evaluate(self, formatter, kwargs, mi, locals, name):
return formatter.get_value(name, [], kwargs)
@@ -360,7 +363,7 @@ class BuiltinRawField(BuiltinFormatterFunction):
name = 'raw_field'
arg_count = 1
category = 'Get values from metadata'
__doc__ = doc = _('raw_field(name) -- returns the metadata field named by name '
__doc__ = doc = ('raw_field(name) -- returns the metadata field named by name '
'without applying any formatting.')
def evaluate(self, formatter, kwargs, mi, locals, name):
@@ -377,7 +380,7 @@ class BuiltinRawList(BuiltinFormatterFunction):
name = 'raw_list'
arg_count = 2
category = 'Get values from metadata'
__doc__ = doc = _('raw_list(name, separator) -- returns the metadata list '
__doc__ = doc = ('raw_list(name, separator) -- returns the metadata list '
'named by name without applying any formatting or sorting and '
'with items separated by separator.')
@@ -392,7 +395,7 @@ class BuiltinSubstr(BuiltinFormatterFunction):
name = 'substr'
arg_count = 3
category = 'String manipulation'
__doc__ = doc = _('substr(str, start, end) -- returns the start\'th through the end\'th '
__doc__ = doc = ('substr(str, start, end) -- returns the start\'th through the end\'th '
'characters of str. The first character in str is the zero\'th '
'character. If end is negative, then it indicates that many '
'characters counting from the right. If end is zero, then it '
@@ -407,7 +410,7 @@ class BuiltinLookup(BuiltinFormatterFunction):
name = 'lookup'
arg_count = -1
category = 'Iterating over values'
__doc__ = doc = _('lookup(val, pattern, field, pattern, field, ..., else_field) -- '
__doc__ = doc = ('lookup(val, pattern, field, pattern, field, ..., else_field) -- '
'like switch, except the arguments are field (metadata) names, not '
'text. The value of the appropriate field will be fetched and used. '
'Note that because composite columns are fields, you can use this '
@@ -422,7 +425,7 @@ class BuiltinLookup(BuiltinFormatterFunction):
else:
return formatter.vformat('{'+args[1].strip()+'}', [], kwargs)
if (len(args) % 2) != 1:
raise ValueError(_('lookup requires either 2 or an odd number of arguments'))
raise ValueError('lookup requires either 2 or an odd number of arguments')
i = 0
while i < len(args):
if i + 1 >= len(args):
@@ -436,7 +439,7 @@ class BuiltinTest(BuiltinFormatterFunction):
name = 'test'
arg_count = 3
category = 'If-then-else'
__doc__ = doc = _('test(val, text if not empty, text if empty) -- return `text if not '
__doc__ = doc = ('test(val, text if not empty, text if empty) -- return `text if not '
'empty` if val is not empty, otherwise return `text if empty`')
def evaluate(self, formatter, kwargs, mi, locals, val, value_if_set, value_not_set):
@@ -450,7 +453,7 @@ class BuiltinContains(BuiltinFormatterFunction):
name = 'contains'
arg_count = 4
category = 'If-then-else'
__doc__ = doc = _('contains(val, pattern, text if match, text if not match) -- checks '
__doc__ = doc = ('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`')
@@ -467,7 +470,7 @@ class BuiltinSwitch(BuiltinFormatterFunction):
name = 'switch'
arg_count = -1
category = 'Iterating over values'
__doc__ = doc = _('switch(val, pattern, value, pattern, value, ..., else_value) -- '
__doc__ = doc = ('switch(val, pattern, value, 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. '
@@ -475,7 +478,7 @@ class BuiltinSwitch(BuiltinFormatterFunction):
def evaluate(self, formatter, kwargs, mi, locals, val, *args):
if (len(args) % 2) != 1:
raise ValueError(_('switch requires an odd number of arguments'))
raise ValueError('switch requires an odd number of arguments')
i = 0
while i < len(args):
if i + 1 >= len(args):
@@ -489,7 +492,7 @@ class BuiltinStrcatMax(BuiltinFormatterFunction):
name = 'strcat_max'
arg_count = -1
category = 'String manipulation'
__doc__ = doc = _('strcat_max(max, string1, prefix2, string2, ...) -- '
__doc__ = doc = ('strcat_max(max, string1, prefix2, string2, ...) -- '
'Returns a string formed by concatenating the arguments. The '
'returned value is initialized to string1. `Prefix, string` '
'pairs are added to the end of the value as long as the '
@@ -499,13 +502,13 @@ class BuiltinStrcatMax(BuiltinFormatterFunction):
def evaluate(self, formatter, kwargs, mi, locals, *args):
if len(args) < 2:
raise ValueError(_('strcat_max requires 2 or more arguments'))
raise ValueError('strcat_max requires 2 or more arguments')
if (len(args) % 2) != 0:
raise ValueError(_('strcat_max requires an even number of arguments'))
raise ValueError('strcat_max requires an even number of arguments')
try:
max = int(args[0])
except:
raise ValueError(_('first argument to strcat_max must be an integer'))
raise ValueError('first argument to strcat_max must be an integer')
i = 2
result = args[1]
@@ -524,7 +527,7 @@ class BuiltinInList(BuiltinFormatterFunction):
name = 'in_list'
arg_count = -1
category = 'List lookup'
__doc__ = doc = _('in_list(val, separator, pattern, found_val, ..., not_found_val) -- '
__doc__ = doc = ('in_list(val, separator, pattern, found_val, ..., not_found_val) -- '
'treat val as a list of items separated by separator, '
'evaluating the pattern against each value in the list. If the '
'pattern matches a value, return found_val, otherwise return '
@@ -535,7 +538,7 @@ class BuiltinInList(BuiltinFormatterFunction):
def evaluate(self, formatter, kwargs, mi, locals, val, sep, *args):
if (len(args) % 2) != 1:
raise ValueError(_('in_list requires an odd number of arguments'))
raise ValueError('in_list requires an odd number of arguments')
l = [v.strip() for v in val.split(sep) if v.strip()]
i = 0
while i < len(args):
@@ -554,7 +557,7 @@ class BuiltinStrInList(BuiltinFormatterFunction):
name = 'str_in_list'
arg_count = -1
category = 'List lookup'
__doc__ = doc = _('str_in_list(val, separator, string, found_val, ..., not_found_val) -- '
__doc__ = doc = ('str_in_list(val, separator, string, found_val, ..., not_found_val) -- '
'treat val as a list of items separated by separator, '
'comparing the string against each value in the list. If the '
'string matches a value (ignoring case) then return found_val, otherwise return '
@@ -566,7 +569,7 @@ class BuiltinStrInList(BuiltinFormatterFunction):
def evaluate(self, formatter, kwargs, mi, locals, val, sep, *args):
if (len(args) % 2) != 1:
raise ValueError(_('str_in_list requires an odd number of arguments'))
raise ValueError('str_in_list requires an odd number of arguments')
l = [v.strip() for v in val.split(sep) if v.strip()]
i = 0
while i < len(args):
@@ -587,7 +590,7 @@ class BuiltinIdentifierInList(BuiltinFormatterFunction):
name = 'identifier_in_list'
arg_count = 4
category = 'List lookup'
__doc__ = doc = _('identifier_in_list(val, id, found_val, not_found_val) -- '
__doc__ = doc = ('identifier_in_list(val, id, found_val, not_found_val) -- '
'treat val as a list of identifiers separated by commas, '
'comparing the string against each value in the list. An identifier '
'has the format "identifier:value". The id parameter should be '
@@ -614,7 +617,7 @@ class BuiltinRe(BuiltinFormatterFunction):
name = 're'
arg_count = 3
category = 'String manipulation'
__doc__ = doc = _('re(val, pattern, replacement) -- return val after applying '
__doc__ = doc = ('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')
@@ -627,7 +630,7 @@ class BuiltinReGroup(BuiltinFormatterFunction):
name = 're_group'
arg_count = -1
category = 'String manipulation'
__doc__ = doc = _('re_group(val, pattern, template_for_group_1, for_group_2, ...) -- '
__doc__ = doc = ('re_group(val, pattern, template_for_group_1, for_group_2, ...) -- '
'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 '
@@ -662,7 +665,7 @@ class BuiltinSwapAroundComma(BuiltinFormatterFunction):
name = 'swap_around_comma'
arg_count = 1
category = 'String manipulation'
__doc__ = doc = _('swap_around_comma(val) -- given a value of the form '
__doc__ = doc = ('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')
@@ -675,7 +678,7 @@ class BuiltinIfempty(BuiltinFormatterFunction):
name = 'ifempty'
arg_count = 2
category = 'If-then-else'
__doc__ = doc = _('ifempty(val, text if empty) -- return val if val is not empty, '
__doc__ = doc = ('ifempty(val, text if empty) -- return val if val is not empty, '
'otherwise return `text if empty`')
def evaluate(self, formatter, kwargs, mi, locals, val, value_if_empty):
@@ -689,7 +692,7 @@ class BuiltinShorten(BuiltinFormatterFunction):
name = 'shorten'
arg_count = 4
category = 'String manipulation'
__doc__ = doc = _('shorten(val, left chars, middle text, right chars) -- Return a '
__doc__ = doc = ('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 '
@@ -716,7 +719,7 @@ class BuiltinCount(BuiltinFormatterFunction):
name = 'count'
arg_count = 2
category = 'List manipulation'
__doc__ = doc = _('count(val, separator) -- interprets the value as a list of items '
__doc__ = doc = ('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(&)}')
@@ -729,7 +732,7 @@ class BuiltinListitem(BuiltinFormatterFunction):
name = 'list_item'
arg_count = 3
category = 'List lookup'
__doc__ = doc = _('list_item(val, index, separator) -- interpret the value as a list of '
__doc__ = doc = ('list_item(val, index, separator) -- interpret the value as a list of '
'items separated by `separator`, returning the `index`th item. '
'The first item is number zero. The last item can be returned '
'using `list_item(-1,separator)`. If the item is not in the list, '
@@ -751,7 +754,7 @@ class BuiltinSelect(BuiltinFormatterFunction):
name = 'select'
arg_count = 2
category = 'List lookup'
__doc__ = doc = _('select(val, key) -- interpret the value as a comma-separated list '
__doc__ = doc = ('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.'
)
@@ -770,7 +773,7 @@ class BuiltinApproximateFormats(BuiltinFormatterFunction):
name = 'approximate_formats'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('approximate_formats() -- return a comma-separated '
__doc__ = doc = ('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. '
@@ -791,14 +794,14 @@ class BuiltinApproximateFormats(BuiltinFormatterFunction):
return ''
data = sorted(fmt_data)
return ','.join(v.upper() for v in data)
return _('This function can be used only in the GUI')
return 'This function can be used only in the GUI'
class BuiltinFormatsModtimes(BuiltinFormatterFunction):
name = 'formats_modtimes'
arg_count = 1
category = 'Get values from metadata'
__doc__ = doc = _('formats_modtimes(date_format) -- return a comma-separated '
__doc__ = doc = ('formats_modtimes(date_format) -- return a comma-separated '
'list of colon-separated items representing modification times '
'for the formats of a book. The date_format parameter '
'specifies how the date is to be formatted. See the '
@@ -822,7 +825,7 @@ class BuiltinFormatsSizes(BuiltinFormatterFunction):
name = 'formats_sizes'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('formats_sizes() -- return a comma-separated list of '
__doc__ = doc = ('formats_sizes() -- return a comma-separated list of '
'colon-separated items representing sizes in bytes '
'of the formats of a book. You can use the select '
'function to get the size for a specific '
@@ -842,7 +845,7 @@ class BuiltinFormatsPaths(BuiltinFormatterFunction):
name = 'formats_paths'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('formats_paths() -- return a comma-separated list of '
__doc__ = doc = ('formats_paths() -- return a comma-separated list of '
'colon-separated items representing full path to '
'the formats of a book. You can use the select '
'function to get the path for a specific '
@@ -861,7 +864,7 @@ class BuiltinHumanReadable(BuiltinFormatterFunction):
name = 'human_readable'
arg_count = 1
category = 'Formatting values'
__doc__ = doc = _('human_readable(v) -- return a string '
__doc__ = doc = ('human_readable(v) -- return a string '
'representing the number v in KB, MB, GB, etc.'
)
@@ -876,7 +879,7 @@ class BuiltinFormatNumber(BuiltinFormatterFunction):
name = 'format_number'
arg_count = 2
category = 'Formatting values'
__doc__ = doc = _('format_number(v, template) -- format the number v using '
__doc__ = doc = ('format_number(v, template) -- format the number v using '
'a Python formatting template such as "{0:5.2f}" or '
'"{0:,d}" or "${0:5,.2f}". The field_name part of the '
'template must be a 0 (zero) (the "{0:" in the above examples). '
@@ -912,7 +915,7 @@ class BuiltinSublist(BuiltinFormatterFunction):
name = 'sublist'
arg_count = 4
category = 'List manipulation'
__doc__ = doc = _('sublist(val, start_index, end_index, separator) -- interpret the '
__doc__ = doc = ('sublist(val, start_index, end_index, separator) -- interpret the '
'value as a list of items separated by `separator`, returning a '
'new list made from the `start_index` to the `end_index` item. '
'The first item is number zero. If an index is negative, then it '
@@ -948,7 +951,7 @@ class BuiltinSubitems(BuiltinFormatterFunction):
name = 'subitems'
arg_count = 3
category = 'List manipulation'
__doc__ = doc = _('subitems(val, start_index, end_index) -- This function is used to '
__doc__ = doc = ('subitems(val, start_index, end_index) -- This function is used to '
'break apart lists of items such as genres. It interprets the value '
'as a comma-separated list of items, where each item is a period-'
'separated list. Returns a new list made by first finding all the '
@@ -993,7 +996,7 @@ class BuiltinFormatDate(BuiltinFormatterFunction):
name = 'format_date'
arg_count = 2
category = 'Formatting values'
__doc__ = doc = _('format_date(val, format_string) -- format the value, '
__doc__ = doc = ('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) '
@@ -1031,7 +1034,7 @@ class BuiltinUppercase(BuiltinFormatterFunction):
name = 'uppercase'
arg_count = 1
category = 'String case changes'
__doc__ = doc = _('uppercase(val) -- return val in upper case')
__doc__ = doc = 'uppercase(val) -- return val in upper case'
def evaluate(self, formatter, kwargs, mi, locals, val):
return val.upper()
@@ -1041,7 +1044,7 @@ class BuiltinLowercase(BuiltinFormatterFunction):
name = 'lowercase'
arg_count = 1
category = 'String case changes'
__doc__ = doc = _('lowercase(val) -- return val in lower case')
__doc__ = doc = 'lowercase(val) -- return val in lower case'
def evaluate(self, formatter, kwargs, mi, locals, val):
return val.lower()
@@ -1051,7 +1054,7 @@ class BuiltinTitlecase(BuiltinFormatterFunction):
name = 'titlecase'
arg_count = 1
category = 'String case changes'
__doc__ = doc = _('titlecase(val) -- return val in title case')
__doc__ = doc = 'titlecase(val) -- return val in title case'
def evaluate(self, formatter, kwargs, mi, locals, val):
return titlecase(val)
@@ -1061,7 +1064,7 @@ class BuiltinCapitalize(BuiltinFormatterFunction):
name = 'capitalize'
arg_count = 1
category = 'String case changes'
__doc__ = doc = _('capitalize(val) -- return val capitalized')
__doc__ = doc = 'capitalize(val) -- return val capitalized'
def evaluate(self, formatter, kwargs, mi, locals, val):
return capitalize(val)
@@ -1071,7 +1074,7 @@ class BuiltinBooksize(BuiltinFormatterFunction):
name = 'booksize'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('booksize() -- return value of the size field. '
__doc__ = doc = ('booksize() -- return value of the size field. '
'This function works only in the GUI. If you want to use this value '
'in save-to-disk or send-to-device templates then you '
'must make a custom "Column built from other columns", use '
@@ -1088,14 +1091,14 @@ class BuiltinBooksize(BuiltinFormatterFunction):
except:
pass
return ''
return _('This function can be used only in the GUI')
return 'This function can be used only in the GUI'
class BuiltinOndevice(BuiltinFormatterFunction):
name = 'ondevice'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('ondevice() -- return Yes if ondevice is set, otherwise return '
__doc__ = doc = ('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 '
@@ -1105,16 +1108,16 @@ class BuiltinOndevice(BuiltinFormatterFunction):
def evaluate(self, formatter, kwargs, mi, locals):
if hasattr(mi, '_proxy_metadata'):
if mi._proxy_metadata.ondevice_col:
return _('Yes')
return 'Yes'
return ''
return _('This function can be used only in the GUI')
return 'This function can be used only in the GUI'
class BuiltinSeriesSort(BuiltinFormatterFunction):
name = 'series_sort'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('series_sort() -- return the series sort value')
__doc__ = doc = 'series_sort() -- return the series sort value'
def evaluate(self, formatter, kwargs, mi, locals):
if mi.series:
@@ -1126,12 +1129,12 @@ class BuiltinHasCover(BuiltinFormatterFunction):
name = 'has_cover'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('has_cover() -- return Yes if the book has a cover, '
__doc__ = doc = ('has_cover() -- return Yes if the book has a cover, '
'otherwise return the empty string')
def evaluate(self, formatter, kwargs, mi, locals):
if mi.has_cover:
return _('Yes')
return 'Yes'
return ''
@@ -1139,7 +1142,7 @@ class BuiltinFirstNonEmpty(BuiltinFormatterFunction):
name = 'first_non_empty'
arg_count = -1
category = 'Iterating over values'
__doc__ = doc = _('first_non_empty(value, value, ...) -- '
__doc__ = doc = ('first_non_empty(value, value, ...) -- '
'returns the first value that is not empty. If all values are '
'empty, then the empty value is returned. '
'You can have as many values as you want.')
@@ -1157,7 +1160,7 @@ class BuiltinAnd(BuiltinFormatterFunction):
name = 'and'
arg_count = -1
category = 'Boolean'
__doc__ = doc = _('and(value, value, ...) -- '
__doc__ = doc = ('and(value, value, ...) -- '
'returns the string "1" if all values are not empty, otherwise '
'returns the empty string. This function works well with test or '
'first_non_empty. You can have as many values as you want. ')
@@ -1175,7 +1178,7 @@ class BuiltinOr(BuiltinFormatterFunction):
name = 'or'
arg_count = -1
category = 'Boolean'
__doc__ = doc = _('or(value, value, ...) -- '
__doc__ = doc = ('or(value, value, ...) -- '
'returns the string "1" if any value is not empty, otherwise '
'returns the empty string. This function works well with test or '
'first_non_empty. You can have as many values as you want.')
@@ -1193,7 +1196,7 @@ class BuiltinNot(BuiltinFormatterFunction):
name = 'not'
arg_count = 1
category = 'Boolean'
__doc__ = doc = _('not(value) -- '
__doc__ = doc = ('not(value) -- '
'returns the string "1" if the value is empty, otherwise '
'returns the empty string. This function works well with test or '
'first_non_empty.')
@@ -1206,7 +1209,7 @@ class BuiltinListUnion(BuiltinFormatterFunction):
name = 'list_union'
arg_count = 3
category = 'List manipulation'
__doc__ = doc = _('list_union(list1, list2, separator) -- '
__doc__ = doc = ('list_union(list1, list2, separator) -- '
'return a list made by merging the items in list1 and list2, '
'removing duplicate items using a case-insensitive comparison. If '
'items differ in case, the one in list1 is used. '
@@ -1231,7 +1234,7 @@ class BuiltinListDifference(BuiltinFormatterFunction):
name = 'list_difference'
arg_count = 3
category = 'List manipulation'
__doc__ = doc = _('list_difference(list1, list2, separator) -- '
__doc__ = doc = ('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.')
@@ -1253,7 +1256,7 @@ class BuiltinListIntersection(BuiltinFormatterFunction):
name = 'list_intersection'
arg_count = 3
category = 'List manipulation'
__doc__ = doc = _('list_intersection(list1, list2, separator) -- '
__doc__ = doc = ('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.')
@@ -1275,7 +1278,7 @@ class BuiltinListSort(BuiltinFormatterFunction):
name = 'list_sort'
arg_count = 3
category = 'List manipulation'
__doc__ = doc = _('list_sort(list, direction, separator) -- '
__doc__ = doc = ('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.')
@@ -1291,7 +1294,7 @@ class BuiltinListEquals(BuiltinFormatterFunction):
name = 'list_equals'
arg_count = 6
category = 'List manipulation'
__doc__ = doc = _('list_equals(list1, sep1, list2, sep2, yes_val, no_val) -- '
__doc__ = doc = ('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 '
@@ -1310,7 +1313,7 @@ class BuiltinListRe(BuiltinFormatterFunction):
name = 'list_re'
arg_count = 4
category = 'List manipulation'
__doc__ = doc = _('list_re(src_list, separator, include_re, opt_replace) -- '
__doc__ = doc = ('list_re(src_list, separator, include_re, opt_replace) -- '
'Construct a list by first separating src_list into items using '
'the separator character. For each item in the list, check if it '
'matches include_re. If it does, then add it to the list to be '
@@ -1336,7 +1339,7 @@ class BuiltinListReGroup(BuiltinFormatterFunction):
name = 'list_re_group'
arg_count = -1
category = 'List manipulation'
__doc__ = doc = _('list_re_group(src_list, separator, include_re, search_re, group_1_template, ...) -- '
__doc__ = doc = ('list_re_group(src_list, separator, include_re, search_re, group_1_template, ...) -- '
'Like list_re except replacements are not optional. It '
'uses re_group(list_item, search_re, group_1_template, ...) when '
'doing the replacements on the resulting list.')
@@ -1376,7 +1379,7 @@ class BuiltinToday(BuiltinFormatterFunction):
name = 'today'
arg_count = 0
category = 'Date functions'
__doc__ = doc = _('today() -- '
__doc__ = doc = ('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.')
@@ -1389,7 +1392,7 @@ class BuiltinDaysBetween(BuiltinFormatterFunction):
name = 'days_between'
arg_count = 2
category = 'Date functions'
__doc__ = doc = _('days_between(date1, date2) -- '
__doc__ = doc = ('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 '
@@ -1413,7 +1416,7 @@ class BuiltinLanguageStrings(BuiltinFormatterFunction):
name = 'language_strings'
arg_count = 2
category = 'Get values from metadata'
__doc__ = doc = _('language_strings(lang_codes, localize) -- '
__doc__ = doc = ('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 '
@@ -1435,7 +1438,7 @@ class BuiltinLanguageCodes(BuiltinFormatterFunction):
name = 'language_codes'
arg_count = 1
category = 'Get values from metadata'
__doc__ = doc = _('language_codes(lang_strings) -- '
__doc__ = doc = ('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.')
@@ -1456,7 +1459,7 @@ class BuiltinCurrentLibraryName(BuiltinFormatterFunction):
name = 'current_library_name'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('current_library_name() -- '
__doc__ = doc = ('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()\'}".')
@@ -1470,7 +1473,7 @@ class BuiltinCurrentLibraryPath(BuiltinFormatterFunction):
name = 'current_library_path'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('current_library_path() -- '
__doc__ = doc = ('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()\'}".')
@@ -1484,7 +1487,7 @@ class BuiltinFinishFormatting(BuiltinFormatterFunction):
name = 'finish_formatting'
arg_count = 4
category = 'Formatting values'
__doc__ = doc = _('finish_formatting(val, fmt, prefix, suffix) -- apply the '
__doc__ = doc = ('finish_formatting(val, fmt, prefix, suffix) -- apply the '
'format, prefix, and suffix to a value in the same way as '
'done in a template like `{series_index:05.2f| - |- }`. For '
'example, the following program produces the same output '
@@ -1501,7 +1504,7 @@ class BuiltinVirtualLibraries(BuiltinFormatterFunction):
name = 'virtual_libraries'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('virtual_libraries() -- return a comma-separated list of '
__doc__ = doc = ('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 '
@@ -1512,14 +1515,14 @@ class BuiltinVirtualLibraries(BuiltinFormatterFunction):
def evaluate(self, formatter, kwargs, mi, locals_):
if hasattr(mi, '_proxy_metadata'):
return mi._proxy_metadata.virtual_libraries
return _('This function can be used only in the GUI')
return 'This function can be used only in the GUI'
class BuiltinUserCategories(BuiltinFormatterFunction):
name = 'user_categories'
arg_count = 0
category = 'Get values from metadata'
__doc__ = doc = _('user_categories() -- return a comma-separated list of '
__doc__ = doc = ('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 '
@@ -1532,14 +1535,14 @@ class BuiltinUserCategories(BuiltinFormatterFunction):
cats = set(k for k, v in mi._proxy_metadata.user_categories.items() if v)
cats = sorted(cats, key=sort_key)
return ', '.join(cats)
return _('This function can be used only in the GUI')
return 'This function can be used only in the GUI'
class BuiltinTransliterate(BuiltinFormatterFunction):
name = 'transliterate'
arg_count = 1
category = 'String manipulation'
__doc__ = doc = _('transliterate(a) -- Returns a string in a latin alphabet '
__doc__ = doc = ('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 "{0}"'
' the function returns "{1}".').format(
@@ -1554,7 +1557,7 @@ class BuiltinAuthorLinks(BuiltinFormatterFunction):
name = 'author_links'
arg_count = 2
category = 'Get values from metadata'
__doc__ = doc = _('author_links(val_separator, pair_separator) -- returns '
__doc__ = doc = ('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 '
@@ -1573,14 +1576,14 @@ class BuiltinAuthorLinks(BuiltinFormatterFunction):
return ''
names = sorted(link_data.keys(), key=sort_key)
return pair_sep.join(n + val_sep + link_data[n] for n in names)
return _('This function can be used only in the GUI')
return 'This function can be used only in the GUI'
class BuiltinAuthorSorts(BuiltinFormatterFunction):
name = 'author_sorts'
arg_count = 1
category = 'Get values from metadata'
__doc__ = doc = _('author_sorts(val_separator) -- returns a string '
__doc__ = doc = ('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 (different from the author_sort in books). The '

View File

@@ -9,7 +9,7 @@ def html2text(html):
r'<\s*(?P<solidus>/?)\s*[uU]\b(?P<rest>[^>]*)>',
r'<\g<solidus>span\g<rest>>', html)
h2t = HTML2Text()
h2t.default_image_alt = _('Unnamed image')
h2t.default_image_alt = 'Unnamed image'
h2t.body_width = 0
h2t.single_line_break = True
h2t.emphasis_mark = '*'

View File

@@ -2,9 +2,10 @@ __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import re, io, sys
import re
import io
import sys
import json
from gettext import GNUTranslations, NullTranslations
import pkg_resources
_available_translations = None
@@ -62,101 +63,92 @@ def load_po(path):
return buf
def set_translators():
t = NullTranslations()
set_translators.lang = t.info().get('language')
t.install(names=('ngettext',))
set_translators.lang = None
_iso639 = None
_extra_lang_codes = {
'pt_BR' : _('Brazilian Portuguese'),
'en_GB' : _('English (UK)'),
'zh_CN' : _('Simplified Chinese'),
'zh_TW' : _('Traditional Chinese'),
'en' : _('English'),
'en_US' : _('English (United States)'),
'en_AR' : _('English (Argentina)'),
'en_AU' : _('English (Australia)'),
'en_JP' : _('English (Japan)'),
'en_DE' : _('English (Germany)'),
'en_BG' : _('English (Bulgaria)'),
'en_EG' : _('English (Egypt)'),
'en_NZ' : _('English (New Zealand)'),
'en_CA' : _('English (Canada)'),
'en_GR' : _('English (Greece)'),
'en_IN' : _('English (India)'),
'en_NP' : _('English (Nepal)'),
'en_TH' : _('English (Thailand)'),
'en_TR' : _('English (Turkey)'),
'en_CY' : _('English (Cyprus)'),
'en_CZ' : _('English (Czech Republic)'),
'en_PH' : _('English (Philippines)'),
'en_PK' : _('English (Pakistan)'),
'en_PL' : _('English (Poland)'),
'en_HR' : _('English (Croatia)'),
'en_HU' : _('English (Hungary)'),
'en_ID' : _('English (Indonesia)'),
'en_IL' : _('English (Israel)'),
'en_RU' : _('English (Russia)'),
'en_SG' : _('English (Singapore)'),
'en_YE' : _('English (Yemen)'),
'en_IE' : _('English (Ireland)'),
'en_CN' : _('English (China)'),
'en_TW' : _('English (Taiwan)'),
'en_ZA' : _('English (South Africa)'),
'es_PY' : _('Spanish (Paraguay)'),
'es_UY' : _('Spanish (Uruguay)'),
'es_AR' : _('Spanish (Argentina)'),
'es_CR' : _('Spanish (Costa Rica)'),
'es_MX' : _('Spanish (Mexico)'),
'es_CU' : _('Spanish (Cuba)'),
'es_CL' : _('Spanish (Chile)'),
'es_EC' : _('Spanish (Ecuador)'),
'es_HN' : _('Spanish (Honduras)'),
'es_VE' : _('Spanish (Venezuela)'),
'es_BO' : _('Spanish (Bolivia)'),
'es_NI' : _('Spanish (Nicaragua)'),
'es_CO' : _('Spanish (Colombia)'),
'de_AT' : _('German (AT)'),
'fr_BE' : _('French (BE)'),
'nl' : _('Dutch (NL)'),
'nl_BE' : _('Dutch (BE)'),
'und' : _('Unknown')
'pt_BR' : 'Brazilian Portuguese',
'en_GB' : 'English (UK)',
'zh_CN' : 'Simplified Chinese',
'zh_TW' : 'Traditional Chinese',
'en' : 'English',
'en_US' : 'English (United States)',
'en_AR' : 'English (Argentina)',
'en_AU' : 'English (Australia)',
'en_JP' : 'English (Japan)',
'en_DE' : 'English (Germany)',
'en_BG' : 'English (Bulgaria)',
'en_EG' : 'English (Egypt)',
'en_NZ' : 'English (New Zealand)',
'en_CA' : 'English (Canada)',
'en_GR' : 'English (Greece)',
'en_IN' : 'English (India)',
'en_NP' : 'English (Nepal)',
'en_TH' : 'English (Thailand)',
'en_TR' : 'English (Turkey)',
'en_CY' : 'English (Cyprus)',
'en_CZ' : 'English (Czech Republic)',
'en_PH' : 'English (Philippines)',
'en_PK' : 'English (Pakistan)',
'en_PL' : 'English (Poland)',
'en_HR' : 'English (Croatia)',
'en_HU' : 'English (Hungary)',
'en_ID' : 'English (Indonesia)',
'en_IL' : 'English (Israel)',
'en_RU' : 'English (Russia)',
'en_SG' : 'English (Singapore)',
'en_YE' : 'English (Yemen)',
'en_IE' : 'English (Ireland)',
'en_CN' : 'English (China)',
'en_TW' : 'English (Taiwan)',
'en_ZA' : 'English (South Africa)',
'es_PY' : 'Spanish (Paraguay)',
'es_UY' : 'Spanish (Uruguay)',
'es_AR' : 'Spanish (Argentina)',
'es_CR' : 'Spanish (Costa Rica)',
'es_MX' : 'Spanish (Mexico)',
'es_CU' : 'Spanish (Cuba)',
'es_CL' : 'Spanish (Chile)',
'es_EC' : 'Spanish (Ecuador)',
'es_HN' : 'Spanish (Honduras)',
'es_VE' : 'Spanish (Venezuela)',
'es_BO' : 'Spanish (Bolivia)',
'es_NI' : 'Spanish (Nicaragua)',
'es_CO' : 'Spanish (Colombia)',
'de_AT' : 'German (AT)',
'fr_BE' : 'French (BE)',
'nl' : 'Dutch (NL)',
'nl_BE' : 'Dutch (BE)',
'und' : 'Unknown'
}
if False:
# Extra strings needed for Qt
# NOTE: Ante Meridian (i.e. like 10:00 AM)
_('AM')
'AM'
# NOTE: Post Meridian (i.e. like 10:00 PM)
_('PM')
'PM'
# NOTE: Ante Meridian (i.e. like 10:00 am)
_('am')
'am'
# NOTE: Post Meridian (i.e. like 10:00 pm)
_('pm')
_('&Copy')
_('Select All')
_('Copy Link')
_('&Select All')
_('Copy &Link Location')
_('&Undo')
_('&Redo')
_('Cu&t')
_('&Paste')
_('Paste and Match Style')
_('Directions')
_('Left to Right')
_('Right to Left')
_('Fonts')
_('&Step up')
_('Step &down')
_('Close without Saving')
_('Close Tab')
'pm'
'&Copy'
'Select All'
'Copy Link'
'&Select All'
'Copy &Link Location'
'&Undo'
'&Redo'
'Cu&t'
'&Paste'
'Paste and Match Style'
'Directions'
'Left to Right'
'Right to Left'
'Fonts'
'&Step up'
'Step &down'
'Close without Saving'
'Close Tab'
_lcase_map = {}
for k in _extra_lang_codes:
@@ -227,15 +219,6 @@ def get_iso_language(lang_trans, lang):
return lang_trans(ans)
def get_language(lang):
translate = _
lang = _lcase_map.get(lang, lang)
if lang in _extra_lang_codes:
# The translator was not active when _extra_lang_codes was defined, so
# re-translate
return translate(_extra_lang_codes[lang])
attr = 'gettext' if sys.version_info.major > 2 else 'ugettext'
return get_iso_language(getattr(_lang_trans, attr, translate), lang)
def calibre_langcode_to_name(lc, localize=True):